<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Java扩展类1：Swing程序设计和高级事件, blog">
    <meta name="description" content="这是我的个人网站，欢迎来访">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Java扩展类1：Swing程序设计和高级事件 | 头号咸鱼</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

    <script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/7b318e23.js","daovoice")</script>
    

<meta name="generator" content="Hexo 5.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="头号咸鱼" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">头号咸鱼</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">头号咸鱼</div>
        <div class="logo-desc">
            
            这是我的个人网站，欢迎来访
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-dg37eo.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Java扩展类1：Swing程序设计和高级事件</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                                <span class="chip bg-color">编程语言</span>
                            </a>
                        
                            <a href="/tags/Java%E6%89%A9%E5%B1%95%E7%B1%BB/">
                                <span class="chip bg-color">Java扩展类</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-02-19
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-02-19
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    25.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    126 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、Swing程序设计"><a href="#一、Swing程序设计" class="headerlink" title="一、Swing程序设计"></a>一、Swing程序设计</h2><h4 id="1-Swing概述"><a href="#1-Swing概述" class="headerlink" title="1.Swing概述"></a>1.Swing概述</h4><blockquote>
<p>原来的AWT组件来自java.awt包，当含有AWT组件的Java应用程序在不同的平台上执行时，每个平台的GUI组件的显示会有所不同，但是在不同平台上运行使用Swing开发的应用程序时，就可以统一GUI组件的显示风格，因为Swing组件允许编程人员在跨平台时指定统一的外观和风格。</p>
</blockquote>
<ul>
<li>Swing是AWT的增强组件，但不能完全替代，需要出现在同一用户界面中</li>
</ul>
<h6 id="Swing包"><a href="#Swing包" class="headerlink" title="Swing包"></a>Swing包</h6><blockquote>
<p>为了有效地使用Swing组件，必须了解Swing包的层次结构和继承关系，其中比较重要的类是Component类、Container类和JComponent类。</p>
</blockquote>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210216114325.png"></p>
<h6 id="Swing常用组件"><a href="#Swing常用组件" class="headerlink" title="Swing常用组件"></a>Swing常用组件</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210216114355.png"></p>
<h4 id="2-常用窗体"><a href="#2-常用窗体" class="headerlink" title="2.常用窗体"></a>2.常用窗体</h4><h6 id="JFrame框架窗体"><a href="#JFrame框架窗体" class="headerlink" title="JFrame框架窗体"></a>JFrame框架窗体</h6><blockquote>
<p>JFrame窗体是一个<strong>容器</strong>，它是Swing程序中各个组件的载体，可以将JFrame看作是承载这些Swing组件的容器。在开发应用程序时可以通过继承java.swing.JFrame类创建一个窗体，在这个窗口中添加组件，同时为组件设置事件。由于该窗体继承了JFrame类，所以它拥有一些最大化、最小化、关闭的按钮。</p>
</blockquote>
<ul>
<li>语法格式</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">JFrame jf = new JFrame(title);
Container containrer = jf.getContentPane();<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<blockquote>
<p>JFrame对象创建完成后，需要调用getContentPane();方法将窗体转换为容器，在容器中添加组件和布局管理器</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">container.add(new JButton("按钮"));
container.remove(new JButton("按钮"));<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ul>
<li>例子</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;

public class Example1 extends JFrame {
	private static final long serialVersionUID = 1L;

// 定义一个类继承JFrame类
	public void CreateJFrame(String title) { // 定义一个CreateJFrame()方法
		JFrame jf = new JFrame(title); // 实例化一个JFrame对象
		Container container = jf.getContentPane(); // 获取一个容器
		JLabel jl = new JLabel("这是一个JFrame窗体"); // 创建一个JLabel标签
		// 使标签上的文字居中
		jl.setHorizontalAlignment(SwingConstants.CENTER);
		container.add(jl); // 将标签添加到容器中
		container.setBackground(Color.white);//设置容器的背景颜色
		jf.setVisible(true); // 使窗体可视
		jf.setSize(200, 150); // 设置窗体大小
		// 设置窗体关闭方式
		jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	
	public static void main(String args[]){//在主方法中调用createJFrame()方法
		new Example1().CreateJFrame("创建一个JFrame窗体");
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="JDialog窗体"><a href="#JDialog窗体" class="headerlink" title="JDialog窗体"></a>JDialog窗体</h6><blockquote>
<p> JDialog窗体的功能是从一个窗体中弹出另一个窗体，就像是在使用IE浏览器时弹出的确定<strong>对话框</strong>一样。JDialog窗体实质上就是另一种类型的窗体，它与JFrame窗体类似，JDialog窗体在使用时也需要调用getContentPane()方法将窗体转换为容器，然后在容器中设置窗体的特性。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

class MyJDialog extends JDialog { // 创建新类继承JDialog类

	private static final long serialVersionUID = 1L;

	public MyJDialog(MyFrame frame) {
		// 实例化一个JDialog类对象，指定对话框的父窗体、窗体标题和类型
		super(frame, "第一个JDialog窗体", true);
		Container container = getContentPane(); // 创建一个容器
		container.add(new JLabel("这是一个对话框")); // 在容器中添加标签
		setBounds(120, 120, 100, 100); // 设置对话框窗体大小
	}
}

public class MyFrame extends JFrame { // 创建新类

	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		new MyFrame(); // 实例化MyJDialog类对象
	}
	
	public MyFrame() {
		Container container = getContentPane(); // 创建一个容器
		container.setLayout(null);
		JLabel jl = new JLabel("这是一个JFrame窗体"); // 在窗体中设置标签
		// 将标签的文字置于标签中间位置
		jl.setHorizontalAlignment(SwingConstants.CENTER);
		container.add(jl);
		JButton bl = new JButton("弹出对话框"); // 定义一个按钮
		bl.setBounds(10, 10, 100, 21);
		bl.addActionListener(new ActionListener() { // 为按钮添加鼠标单击事件
					public void actionPerformed(ActionEvent e) {
						// 使MyJDialog窗体可见
						new MyJDialog(MyFrame.this).setVisible(true);
					}
				});
		container.add(bl); // 将按钮添加到容器中
		
		container.add(bl);
		container.setBackground(Color.white);
		setSize(200, 200);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setVisible(true);
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-标签组件与图标"><a href="#3-标签组件与图标" class="headerlink" title="3.标签组件与图标"></a>3.标签组件与图标</h4><h6 id="标签的使用"><a href="#标签的使用" class="headerlink" title="标签的使用"></a>标签的使用</h6><blockquote>
<p>标签由JLabel类定义，它的父类为JComponent类。<br>        标签可以显示一行只读文本、一个图像或带图像的文本，它并不能产生任何类型的事件，只是简单地显示文本和图片，但是可以使用标签的特性指定标签上文本的对齐方式。<br>        JLabel类提供了多种构造方法，这样可以创建多种标签，如显示只有文本的标签、只有图标的标签或是包含文本与图标的标签。</p>
</blockquote>
<h6 id="创建图标"><a href="#创建图标" class="headerlink" title="创建图标"></a>创建图标</h6><blockquote>
<p>Swing中的图标可以放置在按钮、标签等组件上，用于描述组件的用途。图标可以用Java支持的图片文件类型进行创建，也可以使用java.awt.Graphics类提供的功能方法来创建。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class DrawIcon implements Icon { // 实现Icon接口
	private int width; // 声明图标的宽
	private int height; // 声明图标的长
	
	public int getIconHeight() { // 实现getIconHeight()方法
		return this.height;
	}
	
	public int getIconWidth() { // 实现getIconWidth()方法
		return this.width;
	}
	
	public DrawIcon(int width, int height) { // 定义构造方法
		this.width = width;
		this.height = height;
	}
	
	// 实现paintIcon()方法
	public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
		arg1.fillOval(x, y, width, height); // 绘制一个圆形
	}
	
	public static void main(String[] args) {
		DrawIcon icon = new DrawIcon(15, 15);
		// 创建一个标签，并设置标签上的文字在标签正中间
		JLabel j = new JLabel("测试", icon, SwingConstants.CENTER);
		JFrame jf = new JFrame(); // 创建一个JFrame窗口
		Container c = jf.getContentPane();
		c.add(j);
		jf.setSize(100,100);
		jf.setVisible(true);
		jf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="使用图片图标"><a href="#使用图片图标" class="headerlink" title="使用图片图标"></a>使用图片图标</h6><pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.net.*;

import javax.swing.*;

public class MyImageIcon extends JFrame {

	private static final long serialVersionUID = 1L;

	public MyImageIcon() {
		Container container = getContentPane();
		// 创建一个标签
		JLabel jl = new JLabel("这是一个JFrame窗体", JLabel.CENTER);
		// 获取图片所在的URL
		URL url = MyImageIcon.class.getResource("imageButton.jpg");
		Icon icon = new ImageIcon(url); // 实例化Icon对象
		jl.setIcon(icon); // 为标签设置图片
		// 设置文字放置在标签中间
		jl.setHorizontalAlignment(SwingConstants.CENTER);
		jl.setOpaque(true); // 设置标签为不透明状态
		container.add(jl); // 将标签添加到容器中
		setSize(250, 100); // 设置窗体大小
		setVisible(true); // 使窗体可见
		// 设置窗体关闭模式
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	
	public static void main(String args[]) {
		new MyImageIcon(); // 实例化MyImageIcon对象
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-常用布局管理器"><a href="#4-常用布局管理器" class="headerlink" title="4.常用布局管理器"></a>4.常用布局管理器</h4><h6 id="绝对布局"><a href="#绝对布局" class="headerlink" title="绝对布局"></a>绝对布局</h6><blockquote>
<p>在Swing中，除了使用布局管理器之外也可以使用绝对布局。绝对布局，顾名思义，就是硬性指定组件在容器中的位置和大小，可以使用绝对坐标的方式来指定组件的位置。</p>
</blockquote>
<ul>
<li>使用绝对布局的步骤如下：<br>（1）使用Container.setLayout(null)方法取消布局管理器。<br>（2）使用Component.setBounds()方法设置每个组件的大小与位置。</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;

public class AbsolutePosition extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public AbsolutePosition() {
		setTitle("本窗体使用绝对布局"); // 设置该窗体的标题
		setLayout(null); // 使该窗体取消布局管理器设置
		setBounds(0, 0, 200, 150); // 绝对定位窗体的位置与大小
		Container c = getContentPane(); // 创建容器对象
		JButton b1 = new JButton("按钮1"); // 创建按钮
		JButton b2 = new JButton("按钮2"); // 创建按钮
		b1.setBounds(10, 30, 80, 30); // 设置按钮的位置与大小
		b2.setBounds(60, 70, 100, 20);
		c.add(b1); // 将按钮添加到容器中
		c.add(b2);
		setVisible(true); // 使窗体可见
		// 设置窗体关闭方式
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new AbsolutePosition();
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="流布局管理器"><a href="#流布局管理器" class="headerlink" title="流布局管理器"></a>流布局管理器</h6><blockquote>
<p>流布局管理器是布局管理器中最基本的布局管理器。流布局管理器在整个容器中的布局正如其名，像“流”一样从左到右摆放组件，直到占据了这一行的所有空间，然后再向下移动一行。默认情况下，组件在每一行上都是居中排列的，但是通过设置也可以更改组件在每一行上的排列位置。</p>
</blockquote>
<p>FlowLayout类中具有以下常用的构造方法：</p>
<ul>
<li><p>public FlowLayout()</p>
</li>
<li><p>public FlowLayout(int alignment)</p>
</li>
<li><p>public FlowLayout(int alignment,int horizGap,int vertGap)</p>
<blockquote>
<p>构造方法中的alignment参数表示使用流布局管理器后组件在每一行的具体摆放位置。</p>
</blockquote>
</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;

public class FlowLayoutPosition extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public FlowLayoutPosition() {
		setTitle("本窗体使用流布局管理器"); // 设置窗体标题
		Container c = getContentPane();
		// 设置窗体使用流布局管理器，使组件右对齐，并且设置组件之间的水平间隔与垂直间隔
		setLayout(new FlowLayout(2, 10, 10));
		for (int i = 0; i &lt; 10; i++) { // 在容器中循环添加10个按钮
			c.add(new JButton("button" + i));
		}
		setSize(300, 200); // 设置窗体大小
		setVisible(true); // 设置窗体可见
		// 设置窗体关闭方式
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new FlowLayoutPosition();
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="边界布局管理器"><a href="#边界布局管理器" class="headerlink" title="边界布局管理器"></a>边界布局管理器</h6><blockquote>
<p>在默认不指定窗体布局的情况下，Swing组件的布局模式是BorderLayout布局管理器。边界布局管理器可以将容器划分为东、南、西、北、中5个区域，可以将组件加入到这5个区域中。容器调用Container类的add()方法添加组件时可以设置此组件在边界布局管理器中的区域，区域的控制可以由BorderLayout类中的成员变量来决定，这些成员变量的具体含义如下表所示。</p>
</blockquote>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210216125223.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;

public class BorderLayoutPosition extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// 定义组件摆放位置的数组
	String[] border = { BorderLayout.CENTER, BorderLayout.NORTH,
			BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.EAST };
	String[] buttonName = { "center button", "north button",
			"south button", "west button", "east button" };
	
	public BorderLayoutPosition() {
		setTitle("这个窗体使用边界布局管理器");
		Container c = getContentPane(); // 定义一个容器
		setLayout(new BorderLayout()); // 设置容器为边界布局管理器
		for (int i = 0; i &lt; border.length; i++) {
			// 在容器中添加按钮，并设置按钮布局
			c.add(border[i], new JButton(buttonName[i]));
		}
		setSize(350, 200); // 设置窗体大小
		setVisible(true); // 使窗体可视
		// 设置窗体关闭方式
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new BorderLayoutPosition();
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="网格布局管理器"><a href="#网格布局管理器" class="headerlink" title="网格布局管理器"></a>网格布局管理器</h6><blockquote>
<p>网格布局管理器将容器划分为网格，所以组件可以按行和列进行排列。在网格布局管理器中，每一个组件的大小都相同，并且网格中的空格的个数由网格的行数和列数决定，例如一个两行两列的网格能产生4个大小相等的网格。组件从网格的左上角开始，按照从左到右、从上到下的顺序加入到网格中，而且每一个组件都会填满整个网格，改变窗体的大小，组件也会随之而改变大小。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class GridLayoutPosition extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public GridLayoutPosition() {
		Container c = getContentPane();
		// 设置容器使用网格布局管理器，设置7行3列的网格
		setLayout(new GridLayout(7, 3, 5, 5));
		for (int i = 0; i &lt; 20; i++) {
			c.add(new JButton("button" + i)); // 循环添加按钮
		}
		setSize(300, 300);
		setTitle("这是一个使用网格布局管理器的窗体");
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new GridLayoutPosition();
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="5-常用面板"><a href="#5-常用面板" class="headerlink" title="5.常用面板"></a>5.常用面板</h4><h6 id="JPanel面板"><a href="#JPanel面板" class="headerlink" title="JPanel面板"></a>JPanel面板</h6><blockquote>
<p>JPanel面板可以聚集一些组件来布局。读者首先应该明确的是面板也是一种容器，因为它也继承自java.awt.Container类。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class JPanelTest extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public JPanelTest() {
		Container c = getContentPane();
		// 将整个容器设置为2行1列的网格布局
		c.setLayout(new GridLayout(2, 1, 10, 10));
		// 初始化一个面板，设置1行3列的网格布局
		JPanel p1 = new JPanel(new GridLayout(1, 3, 10, 10));
		JPanel p2 = new JPanel(new GridLayout(1, 2, 10, 10));
		JPanel p3 = new JPanel(new GridLayout(1, 2, 10, 10));
		JPanel p4 = new JPanel(new GridLayout(2, 1, 10, 10));
		p1.add(new JButton("1")); // 在面板中添加按钮
		p1.add(new JButton("1"));
		p1.add(new JButton("2"));
		p1.add(new JButton("3"));
		p2.add(new JButton("4"));
		p2.add(new JButton("5"));
		p3.add(new JButton("6"));
		p3.add(new JButton("7"));
		p4.add(new JButton("8"));
		p4.add(new JButton("9"));
		c.add(p1); // 在容器中添加面板
		c.add(p2);
		c.add(p3);
		c.add(p4);
		setTitle("在这个窗体中使用了面板");
		setSize(420, 200);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new JPanelTest();
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="JScrollPane面板"><a href="#JScrollPane面板" class="headerlink" title="JScrollPane面板"></a>JScrollPane面板</h6><blockquote>
<p>在设置界面时，可能会遇到在一个较小的容器窗体中显示一个较大部分的内容的情况，这时可以使用JScrollPane面板。JScrollPane面板是带滚动条的面板，它也是一种容器，但是JScrollPane只能放置一个组件，并且不可以使用布局管理器。如果需要在JScrollPane面板中放置多个组件，需要将多个组件放置在JPanel面板上，然后将JPanel面板作为一个整体组件添加在JScrollPane组件上。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class JScrollPaneTest extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public JScrollPaneTest() {
		Container c = getContentPane(); // 创建容器
		JTextArea ta = new JTextArea(20, 50); // 创建文本区域组件
		JScrollPane sp = new JScrollPane(ta); // 创建JScrollPane面板对象
		c.add(sp); // 将该面板添加到该容器中
		
		setTitle("带滚动条的文字编译器");
		setSize(200, 200);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new JScrollPaneTest();
		
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="6-按钮组件"><a href="#6-按钮组件" class="headerlink" title="6.按钮组件"></a>6.按钮组件</h4><h6 id="提交按钮组件"><a href="#提交按钮组件" class="headerlink" title="提交按钮组件"></a>提交按钮组件</h6><p>Swing中的提交按钮由JButton对象表示，其构造方法主要有如下几种形式。</p>
<ul>
<li><p>public JButton()</p>
</li>
<li><p>public JButton(String text)</p>
</li>
<li><p>public JButton(Icon icon)</p>
</li>
<li><p>public JButton(String text,Icon icon)</p>
<blockquote>
<p> 通过使用上述构造方法，在Swing按钮上不仅能显示文本标签，还可以显示图标。上述构造方法中的第一个构造方法可以生成不带任何文本组件的对象和图标，可以以后使用相应方法为按钮设置指定的文本和图标；其他构造方法都在初始化时指定了按钮上显示的图标或文字。</p>
</blockquote>
</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;
import java.net.*;

import javax.swing.*;

public class JButtonTest extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public JButtonTest() {
		URL url = JButtonTest.class.getResource("imageButtoo.jpg");
		Icon icon = new ImageIcon(url);
		setLayout(new GridLayout(3, 2, 5, 5)); // 设置网格布局管理器
		Container c = getContentPane(); // 创建容器
		for (int i = 0; i &lt; 5; i++) {
			// 创建按钮，同时设置按钮文字与图标
			JButton J = new JButton("button" + i, icon);
			c.add(J); // 在容器中添加按钮
			if (i % 2 == 0) {
				J.setEnabled(false); // 设置其中一些按钮不可用
			}
		}
		JButton jb = new JButton(); // 实例化一个没有文字与图片的按钮
		jb.setMaximumSize(new Dimension(90, 30)); // 设置按钮与图片相同大小
		jb.setIcon(icon); // 为按钮设置图标
		jb.setHideActionText(true);
		jb.setToolTipText("图片按钮"); // 设置按钮提示为文字
		jb.setBorderPainted(false); // 设置按钮边界不显示
		jb.addActionListener(new ActionListener() { // 为按钮添加监听事件
					public void actionPerformed(ActionEvent e) {
						// 弹出确认对话框
						JOptionPane.showMessageDialog(null, "弹出对话框");
					}
				});
		c.add(jb); // 将按钮添加到容器中
		
		setTitle("创建带文字与图片的按钮");
		setSize(350, 150);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
	
	public static void main(String args[]) {
		new JButtonTest();
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="单选按钮组件"><a href="#单选按钮组件" class="headerlink" title="单选按钮组件"></a>单选按钮组件</h6><blockquote>
<p>在默认情况下，单选按钮显示一个圆形图标，并且通常在该图标旁放置一些说明性文字，而在应用程序中，一般将多个单选按钮放置在按钮组中，使这些单选按钮表现出某种功能，当用户选中某个单选按钮后，按钮组中其他按钮将被自动取消。单选按钮是Swing组件中JRadioButton类的对象，该类是JToggleButton的子类，而JToggleButton类又是AbstractButton类的子类，所以控制单选按钮的诸多方法都是AbstractButton类中方法。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">JRadioButton jr1 = new JRadioButton();
JRadioButton jr2 = new JRadioButton();
JRadioButton jr3 = new JRadioButton();
ButtonGroup group = new ButtonGroup();
group.add(jr1)
group.add(jr2)
group.add(jr3)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="复选框组件"><a href="#复选框组件" class="headerlink" title="复选框组件"></a>复选框组件</h6><blockquote>
<p>复选框在Swing组件中使用也非常广泛，它具有一个方块图标，外加一段描述性文字。与单选按钮唯一不同的是复选框可以进行多选设置，每一个复选框都提供“选择”与“不选择”两种状态。复选框由JCheckBox类的对象表示，它同样继承于AbstractButton类，所以复选框组件的属性设置也来源于AbstractButton类。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class CheckBoxTest extends JFrame{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel panel1 = new JPanel();
	private JPanel panel2 = new JPanel();
	private JTextArea jt=new JTextArea(3,10);
	private JCheckBox jc1=new JCheckBox("1");
	private JCheckBox jc2=new JCheckBox("2");
	private JCheckBox jc3=new JCheckBox("3");
	public CheckBoxTest(){
		Container c=getContentPane();
		setSize(200,160);
		setVisible(true);
		setTitle("复选框的使用");
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		c.setLayout(new BorderLayout());

		
		c.add(panel1, BorderLayout.NORTH);
		final JScrollPane scrollPane = new JScrollPane(jt);
		panel1.add(scrollPane);


		c.add(panel2, BorderLayout.SOUTH);
		panel2.add(jc1);
		jc1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(jc1.isSelected())
				jt.append("复选框1被选中\n");
			}
		});

		panel2.add(jc2);
		jc2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(jc2.isSelected())
				jt.append("复选框2被选中\n");
			}
		});

		panel2.add(jc3);
		jc3.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(jc3.isSelected())
				jt.append("复选框3被选中\n");
			}
		});
	}
	
	public static void main(String[] args) {
		new CheckBoxTest();

	}

}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="7-列表组件"><a href="#7-列表组件" class="headerlink" title="7.列表组件"></a>7.列表组件</h4><h6 id="下拉列表框组件"><a href="#下拉列表框组件" class="headerlink" title="下拉列表框组件"></a>下拉列表框组件</h6><blockquote>
<p>初次使用Swing中的下拉列表框时，会感觉到该此类下拉列表框与Windows操作系统中的下拉列表框有一些相似，实质上两者并不完全相同，因为Swing中的下拉列表框不仅可以从中选择项目，同时也提供用户编辑项目中的内容。<br>        下拉列表框是一个带条状的显示区，它具有下拉功能，在下拉列表框的右方存在一个倒三角形的按钮，当用户单击该按钮，下拉列表框中的项目将会以列表形式显示出来。</p>
</blockquote>
<ul>
<li>JComboBox类</li>
<li>JComboBox类</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class JComboBoxModelTest extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JComboBox&lt;String&gt; jc = new JComboBox&lt;&gt;(new MyComboBox());
	JLabel jl = new JLabel("请选择证件:");
	
	public JComboBoxModelTest() {
		setSize(new Dimension(160, 180));
		setVisible(true);
		setTitle("在窗口中设置下拉列表框");
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		Container cp = getContentPane();
		cp.setLayout(new FlowLayout());
		cp.add(jl);
		cp.add(jc);
	}
	
	public static void main(String[] args) {
		new JComboBoxModelTest();
	}
}

class MyComboBox extends AbstractListModel&lt;String&gt; implements ComboBoxModel&lt;String&gt; {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String selecteditem = null;
	String[] test = { "身份证", "军人证", "学生证", "工作证" };
	
	public String getElementAt(int index) {
		return test[index];
	}
	
	public int getSize() {
		return test.length;
	}
	
	public void setSelectedItem(Object item) {
		selecteditem = (String) item;
	}
	
	public Object getSelectedItem() {
		return selecteditem;
	}
	
	public int getIndex() {
		for (int i = 0; i &lt; test.length; i++) {
			if (test[i].equals(getSelectedItem()))
				return i;
		}
		return 0;
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="列表框组件"><a href="#列表框组件" class="headerlink" title="列表框组件"></a>列表框组件</h6><blockquote>
<p>列表框与下拉列表框的区别不仅仅表现在外观上，当激活下拉列表框时，会出现下拉列表框中的内容，但列表框只是在窗体上占据固定的大小，如果需要列表框具有滚动效果，可以将列表框放入滚动面板中。用户在选择列表框中的某一项时，按住Shift键并选择列表框中的其他项目，其他项目也将被选中；也可以按住Ctrl键并单击列表框中的项目，这样列表框中的项目处于非选择状态。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class JListTest extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public JListTest() {
		Container cp = getContentPane();
		
		cp.setLayout(null);
		JList&lt;String&gt; jl = new JList&lt;&gt;(new MyListModel());
		JScrollPane js = new JScrollPane(jl);
		js.setBounds(10, 10, 100, 100);
		cp.add(js);
		setTitle("在这个窗体中使用了列表框");
		setSize(200, 150);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
	
	public static void main(String args[]) {
		new JListTest();
	}
}

class MyListModel extends AbstractListModel&lt;String&gt; {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] contents = { "列表1", "列表2", "列表3", "列表4", "列表5", "列表6" };
	
	public String getElementAt(int x) {
		if (x &lt; contents.length)
			return contents[x++];
		else
			return null;
	}
	
	public int getSize() {
		return contents.length;
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="8-文本组件"><a href="#8-文本组件" class="headerlink" title="8.文本组件"></a>8.文本组件</h4><h6 id="文本框组件"><a href="#文本框组件" class="headerlink" title="文本框组件"></a>文本框组件</h6><p>文本框用来显示或编辑一个单行文本，在Swing中通过javax.swing.JTextField类对象创建，该类继承了javax.swing.text.JTextComponent类。下面列举了一些创建文本框常用的构造方法。</p>
<ul>
<li><p>public JTextField()</p>
</li>
<li><p>public JTextField(String text)</p>
</li>
<li><p>public JTextField(int fieldwidth)</p>
</li>
<li><p>public JTextField(String text,int fieldwidth)</p>
</li>
<li><p>public JTextField(Document docModel,String text,int fieldWidth)</p>
<blockquote>
<p>在上述构造方法中可以看出，定义JTextField组件很简单，可以在初始化文本框时设置文本框的默认文字、文本框的长度等。</p>
</blockquote>
</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class JTextFieldTest extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public JTextFieldTest(){
		setSize(250,100);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		Container cp=getContentPane();
		getContentPane().setLayout(new FlowLayout());
		final JTextField jt=new JTextField("aaa",20);
		final JButton jb=new JButton("清除");
		cp.add(jt);
		cp.add(jb);
		jt.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				// TODO 自动生成方法存根
				jt.setText("触发事件");
			}
		});
		jb.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				jt.setText("");
				jt.requestFocus();
			}
		});	
		setVisible(true);
	}
	public static void main(String[] args) {
		new JTextFieldTest();
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="密码框组件"><a href="#密码框组件" class="headerlink" title="密码框组件"></a>密码框组件</h6><p>密码框与文本框的定义与用法基本相同，唯一不同的是密码使用户输入的字符串以某种符号进行加密。密码框对象是通过javax.swing.JPasswordField类来创建，JPasswordField类的构造方法JTextField类的构造方法非常相似。下面列举几个常用的构造方法。</p>
<ul>
<li>public JPasswordField()</li>
<li>public JPasswordFiled(String text)</li>
<li>public JPasswordField(int fieldwidth)</li>
<li>public JPasswordField(String text,int fieldwidth)</li>
<li>public JPasswordField(Document docModel,String text,int fieldWidth)</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">JPasswordField jp = new JPasswordField();
jp.setEchoChar('#');<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h6 id="文本域组件"><a href="#文本域组件" class="headerlink" title="文本域组件"></a>文本域组件</h6><p>Swing中任何一个文本区域都是JTextArea类型的对象。JTextArea常用的构造方法如下：</p>
<ul>
<li>public JTextArea()</li>
<li>public JTextArea(String text)</li>
<li>public JTextArea(int rows,int columns)</li>
<li>public JTextArea(Document doc)</li>
<li>public JTextArea(Document doc,String Text,int rows,int columns)<br>在上述构造方法中，可以在初始化文本域时提供默认文本以及文本域的长与宽。</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class JTextAreaTest extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public JTextAreaTest(){
		setSize(200,100);
		setTitle("定义自动换行的文本域");
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		Container cp=getContentPane();
		JTextArea jt=new JTextArea("文本域",6,6);
		jt.setLineWrap(true);//可以自动换行
		cp.add(jt);
		setVisible(true);
	}
	public static void main(String[] args) {
		new JTextAreaTest();
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="9-常用事件监听器"><a href="#9-常用事件监听器" class="headerlink" title="9.常用事件监听器"></a>9.常用事件监听器</h4><h6 id="监听事件简介"><a href="#监听事件简介" class="headerlink" title="监听事件简介"></a>监听事件简介</h6><ul>
<li>在Swing事件模型中由3个分离的对象完成对事件的处理，分别为事件源、事件以及监听程序。事件源触发一个事件，它被一个或多个“监听器”接收，监听器负责处理事件。</li>
<li>所谓事件监听器，实质上就是一个“实现特定类型监听器接口”的类对象。也许有些读者对此有些迷惑，下面就来解释一下。事件几乎都以对象来表示，它是某种事件类的对象，事件源（如按钮）会在用户作出相应的动作（如按钮被按下）时产生事件对象，如动作事件对应ActionEvent类对象，同时要编写一个监听器的类必须实现相应的接口，如ActionEvent类对应的是ActionListener接口，需要获取某个事件对象就必须实现相应的接口，同时需要将接口中的方法一一实现。最后事件源（按钮）调用相应的方法加载这个“实现特定类型监听器接口”的类对象，所有的事件源都具有addXXXListener()和removeXXXListener()方法（其中“XXX”方法表示监听事件类型），这样就可以为组件添加或移除相应的事件监听器。</li>
</ul>
<h6 id="动作事件监听器"><a href="#动作事件监听器" class="headerlink" title="动作事件监听器"></a>动作事件监听器</h6><blockquote>
<p>动作事件（ActionEvent）监听器是Swing中比较常用的事件监听器，很多组件的动作都会使用它监听，如按钮被按下。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class SimpleEvent extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton jb=new JButton("我是按钮，单击我");
	public SimpleEvent(){
		setLayout(null);
		setSize(200,100);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		Container cp=getContentPane();
		cp.add(jb);
		jb.setBounds(10, 10,100,30);
		jb.addActionListener(new jbAction());
		setVisible(true);
	}
	class jbAction implements ActionListener{
		public void actionPerformed(ActionEvent arg0) {
			jb.setText("我被单击了");
		}
	}
	public static void main(String[] args) {
		new SimpleEvent();
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="焦点事件监听器"><a href="#焦点事件监听器" class="headerlink" title="焦点事件监听器"></a>焦点事件监听器</h6><blockquote>
<p>焦点事件（FocusEvent）监听器在实际项目开发中应用也比较广泛，如将光标焦点离开一个文本框时需要弹出一个对话框，或者将焦点返回给该文本框等。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class FocusEventTest extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public FocusEventTest() {
		setSize(250,100);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		Container cp=getContentPane();
		getContentPane().setLayout(new FlowLayout());

		final JLabel label = new JLabel();
		getContentPane().add(label);
		JTextField jt=new JTextField("请单击其他文本框",10);
		JTextField jt2=new JTextField("请单击我",10);
		cp.add(jt);
		cp.add(jt2);
		jt.addFocusListener(new FocusListener(){
			//组件失去焦点时调用的方法 
			public void focusLost(FocusEvent arg0) {
				JOptionPane.showMessageDialog(null, "文本框失去焦点");
			}
			//组件获取键盘焦点时调用的方法
			public void focusGained(FocusEvent arg0) {
			}
		});
		setVisible(true);
	}
	public static void main(String[] args) {
		new FocusEventTest();
	}

}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="作业"><a href="#作业" class="headerlink" title="作业"></a>作业</h6><ul>
<li>窗体</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;

import javax.swing.*;

public class UseCase1 extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JComboBox&lt;String&gt; comboBox;
	public static void main(String[] args) {
		new UseCase1();

	}
	public UseCase1() {
		super();
		setVisible(true);
		setSize(200,150);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		comboBox = new JComboBox&lt;&gt;();
		comboBox.addItem("红");
		comboBox.addItem("黄");
		comboBox.addItem("蓝");
		comboBox.addItem("黑");
		getContentPane().add(comboBox, BorderLayout.NORTH);

		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.CENTER);

		final JCheckBox checkBox = new JCheckBox();
		checkBox.setText("男");
		panel.add(checkBox);

		final JCheckBox checkBox_1 = new JCheckBox();
		checkBox_1.setText("女");
		panel.add(checkBox_1);

		final JPanel panel_1 = new JPanel();
		getContentPane().add(panel_1, BorderLayout.SOUTH);

		final JButton okButton = new JButton();
		okButton.setText("确定");
		panel_1.add(okButton);

		final JButton button_1 = new JButton();
		button_1.setText("取消");
		panel_1.add(button_1);
	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>布局窗体</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class UseCase2 extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] contents={"列表1","列表2","列表3","列表4","列表5"};
	private JComboBox&lt;String&gt; jc=new JComboBox&lt;&gt;();
	private JButton jb=new JButton("提交");
	int count=0;
	public UseCase2() {
		setSize(200, 100);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		Container cp=getContentPane();
		cp.setLayout(new FlowLayout());
		cp.add(jc);
		cp.add(jb);
		jb.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				if(count&lt;contents.length){
					jc.addItem(contents[count++]);
				}
			}
		});
		
	}
	public static void main(String[] args) {
		new UseCase2();

	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>登陆窗</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class UseCase3 extends JFrame{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public UseCase3(){
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("登录窗体");
		setBounds(300, 200, 300, 150);
		Container cp=getContentPane();
		cp.setLayout(null);
		JLabel jl=new JLabel("用户名：");
		jl.setBounds(10, 10, 200, 18);
		final JTextField name=new JTextField();
		name.setBounds(80, 10, 150, 18);
		JLabel jl2=new JLabel("密码：");
		jl2.setBounds(10, 50, 200, 18);
		final JPasswordField password=new JPasswordField();
		password.setBounds(80, 50, 150, 18);
		cp.add(jl);
		cp.add(name);
		cp.add(jl2);
		cp.add(password);
		JButton jb=new JButton("确定");
		jb.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				if(name.getText().trim().length()==0||new String(password.getPassword()).trim().length()==0){
					JOptionPane.showMessageDialog(null, "用户名密码不允许为空");
					return;
				}
				if(name.getText().trim().equals("mr")&amp;&amp;new String(password.getPassword()).trim().equals("mrsoft")){
					JOptionPane.showMessageDialog(null, "登录成功");
				}
				else{
					JOptionPane.showMessageDialog(null, "用户名或密码错误");
				}
			}
		});
		jb.setBounds(80, 80, 60, 18);
		cp.add(jb);

		final JButton button = new JButton();
		button.setText("重置");
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				// TODO 自动生成方法存根
				name.setText("");
				password.setText("");
			}
		});
		button.setBounds(150, 80, 60, 18);
		getContentPane().add(button);
	}
	
	public static void main(String[] args) {
		new UseCase3();

	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="10-表格组件"><a href="#10-表格组件" class="headerlink" title="10.表格组件"></a>10.表格组件</h4><h5 id="利用JTable类直接创建表格"><a href="#利用JTable类直接创建表格" class="headerlink" title="利用JTable类直接创建表格"></a>利用JTable类直接创建表格</h5><h6 id="创建表格"><a href="#创建表格" class="headerlink" title="创建表格"></a>创建表格</h6><blockquote>
<p>利用JTable类直接创建表格</p>
</blockquote>
<p>在JTable类中除了默认的构造方法外，还提供了如下利用指定表格列名数组和表格数据数组创建表格的构造方法。</p>
<pre class="line-numbers language-none"><code class="language-none">JTable(Object[][] rowData, Object[] columnNames)<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li>rowData：封装表格数据的数组</li>
<li>columnNames：封装表格列名的数组</li>
</ul>
<p>在使用表格时，通常将其添加到滚动面板中，然后将滚动面板添加到相应的位置</p>
<ul>
<li>创建可以滚动的表格</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;
public class ExampleFrame_01 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_01 frame = new ExampleFrame_01();
		frame.setVisible(true);
	}
	
	public ExampleFrame_01() {
		super();
		setTitle("创建可以滚动的表格");
		setBounds(100, 100, 240, 150);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		String[] columnNames = { "A", "B" }; // 定义表格列名数组
		// 定义表格数据数组
		String[][] tableValues = { { "A1", "B1" }, { "A2", "B2" },
				{ "A3", "B3" }, { "A4", "B4" }, { "A5", "B5" } };
		// 创建指定列名和数据的表格
		JTable table = new JTable(tableValues, columnNames);
		// 创建显示表格的滚动面板
		JScrollPane scrollPane = new JScrollPane(table);
		// 将滚动面板添加到边界布局的中间
		getContentPane().add(scrollPane, BorderLayout.CENTER);
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217194247.png"></p>
<ul>
<li>创建不可以滚动的表格</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.*;

public class ExampleFrame_02 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_02 frame = new ExampleFrame_02();
		frame.setVisible(true);
	}
	
	public ExampleFrame_02() {
		super();
		setTitle("创建不可滚动的表格");
		setBounds(100, 100, 240, 150);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		Vector&lt;String&gt; columnNameV = new Vector&lt;&gt;();// 定义表格列名向量
		columnNameV.add("A");// 添加列名
		columnNameV.add("B");// 添加列名
		Vector&lt;Vector&lt;String&gt;&gt; tableValueV = new Vector&lt;&gt;();// 定义表格数据向量
		for (int row = 1; row &lt; 6; row++) {
			Vector&lt;String&gt; rowV = new Vector&lt;&gt;();// 定义表格行向量
			rowV.add("A" + row);// 添加单元格数据
			rowV.add("B" + row);// 添加单元格数据
			tableValueV.add(rowV);// 将表格行向量添加到表格数据向量中
		}
		// 创建指定表格列名和表格数据的表格
		JTable table = new JTable(tableValueV, columnNameV);
		// 将表格添加到边界布局的中间
		getContentPane().add(table, BorderLayout.CENTER);
		JTableHeader tableHeader = table.getTableHeader();// 获得表格头对象
		// 将表格头添加到边界布局的上方
		getContentPane().add(tableHeader, BorderLayout.NORTH);
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="定制表格"><a href="#定制表格" class="headerlink" title="定制表格"></a>定制表格</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217194324.png"></p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217194334.png"></p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217194349.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.*;

public class ExampleFrame_03 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_03 frame = new ExampleFrame_03();
		frame.setVisible(true);
	}
	
	public ExampleFrame_03() {
		super();
		setTitle("定义表格");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		final JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		String[] columnNames = { "A", "B", "C", "D", "E", "F", "G" };
		Vector&lt;String&gt; columnNameV = new Vector&lt;&gt;();
		for (int column = 0; column &lt; columnNames.length; column++) {
			columnNameV.add(columnNames[column]);
		}
		Vector&lt;Vector&lt;String&gt;&gt; tableValueV = new Vector&lt;&gt;();
		for (int row = 1; row &lt; 21; row++) {
			Vector&lt;String&gt; rowV = new Vector&lt;String&gt;();
			for (int column = 0; column &lt; columnNames.length; column++) {
				rowV.add(columnNames[column] + row);
			}
			tableValueV.add(rowV);
		}
		JTable table = new MTable(tableValueV, columnNameV);
		// 关闭表格列的自动调整功能
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		// 选择模式为单选
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		// 被选择行的背景色为黄色
		table.setSelectionBackground(Color.YELLOW);
		// 被选择行的前景色（文字颜色）为红色
		table.setSelectionForeground(Color.RED);
		table.setRowHeight(30); // 表格的行高为30像素
		scrollPane.setViewportView(table);
	}
	
	private class MTable extends JTable { // 实现自己的表格类
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public MTable(Vector&lt;Vector&lt;String&gt;&gt; rowData, Vector&lt;String&gt; columnNames) {
			super(rowData, columnNames);
		}
		
		@Override
		public JTableHeader getTableHeader() { // 定义表格头
			// 获得表格头对象
			JTableHeader tableHeader = super.getTableHeader();
			tableHeader.setReorderingAllowed(false); // 设置表格列不可重排
			DefaultTableCellRenderer hr = (DefaultTableCellRenderer) tableHeader
					.getDefaultRenderer(); // 获得表格头的单元格对象
			// 设置列名居中显示
			hr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
			return tableHeader;
		}
		
		// 定义单元格
		@Override
		public TableCellRenderer getDefaultRenderer(Class&lt;?&gt; columnClass) {
			DefaultTableCellRenderer cr = (DefaultTableCellRenderer) super
					.getDefaultRenderer(columnClass); // 获得表格的单元格对象
			// 设置单元格内容居中显示
			cr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
			return cr;
		}
		
		@Override
		public boolean isCellEditable(int row, int column) { // 表格不可编辑
			return false;
		}
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="操纵表格"><a href="#操纵表格" class="headerlink" title="操纵表格"></a>操纵表格</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217194408.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;

public class ExampleFrame_04 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTable table;
	
	public static void main(String args[]) {
		ExampleFrame_04 frame = new ExampleFrame_04();
		frame.setVisible(true);
	}
	
	public ExampleFrame_04() {
		super();
		setTitle("操纵表格");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		String[] columnNames = { "A", "B", "C", "D", "E", "F", "G" };
		Vector&lt;String&gt; columnNameV = new Vector&lt;&gt;();
		for (int column = 0; column &lt; columnNames.length; column++) {
			columnNameV.add(columnNames[column]);
		}
		Vector&lt;Vector&lt;String&gt;&gt; tableValueV = new Vector&lt;&gt;();
		for (int row = 1; row &lt; 21; row++) {
			Vector&lt;String&gt; rowV = new Vector&lt;&gt;();
			for (int column = 0; column &lt; columnNames.length; column++) {
				rowV.add(columnNames[column] + row);
			}
			tableValueV.add(rowV);
		}
		
		table = new JTable(tableValueV, columnNameV);
		table.setRowSelectionInterval(1, 3);// 设置选中行
		table.addRowSelectionInterval(5, 5);// 添加选中行
		scrollPane.setViewportView(table);
		
		JPanel buttonPanel = new JPanel();
		getContentPane().add(buttonPanel, BorderLayout.SOUTH);
		
		JButton selectAllButton = new JButton("全部选择");
		selectAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				table.selectAll();// 选中所有行
			}
		});
		buttonPanel.add(selectAllButton);
		
		JButton clearSelectionButton = new JButton("取消选择");
		clearSelectionButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				table.clearSelection();// 取消所有选中行的选择状态
			}
		});
		buttonPanel.add(clearSelectionButton);
		//
		System.out.println("表格共有" + table.getRowCount() + "行"
				+ table.getColumnCount() + "列");
		System.out.println("共有" + table.getSelectedRowCount() + "行被选中");
		System.out.println("第3行的选择状态为：" + table.isRowSelected(2));
		System.out.println("第5行的选择状态为：" + table.isRowSelected(4));
		System.out.println("被选中的第一行的索引是：" + table.getSelectedRow());
		int[] selectedRows = table.getSelectedRows();// 获得所有被选中行的索引
		System.out.print("所有被选中行的索引是：");
		for (int row = 0; row &lt; selectedRows.length; row++) {
			System.out.print(selectedRows[row] + "  ");
		}
		System.out.println();
		System.out.println("列移动前第2列的名称是：" + table.getColumnName(1));
		System.out.println("列移动前第2行第2列的值是：" + table.getValueAt(1, 1));
		table.moveColumn(1, 5);// 将位于索引1的列移动到索引5处
		System.out.println("列移动后第2列的名称是：" + table.getColumnName(1));
		System.out.println("列移动后第2行第2列的值是：" + table.getValueAt(1, 1));
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="表格模型与表格"><a href="#表格模型与表格" class="headerlink" title="表格模型与表格"></a>表格模型与表格</h5><h6 id="利用表格模型创建表格"><a href="#利用表格模型创建表格" class="headerlink" title="利用表格模型创建表格"></a>利用表格模型创建表格</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217194711.png"></p>
<h6 id="维护表格模型"><a href="#维护表格模型" class="headerlink" title="维护表格模型"></a>维护表格模型</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217194739.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.table.*;

public class ExampleFrame_06 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private DefaultTableModel tableModel;// 定义表格模型对象
	private JTable table;// 定义表格对象
	private JTextField aTextField;
	private JTextField bTextField;
	
	public static void main(String args[]) {
		ExampleFrame_06 frame = new ExampleFrame_06();
		frame.setVisible(true);
	}
	
	public ExampleFrame_06() {
		super();
		setTitle("维护表格模型");
		setBounds(100, 100, 510, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		final JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		String[] columnNames = { "A", "B" };// 定义表格列名数组
		String[][] tableValues = { { "A1", "B1" }, { "A2", "B2" },
				{ "A3", "B3" } };// 定义表格数据数组
		// 创建指定表格列名和表格数据的表格模型
		tableModel = new DefaultTableModel(tableValues, columnNames);
		
		table = new JTable(tableModel);// 创建指定表格模型的表格
		table.setRowSorter(new TableRowSorter&lt;&gt;(tableModel));// 设置表格的排序器
		// 设置表格的选择模式为单选
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		// 为表格添加鼠标事件监听器
		table.addMouseListener(new MouseAdapter() {
			// 发生了点击事件
			public void mouseClicked(MouseEvent e) {
				// 获得被选中行的索引
				int selectedRow = table.getSelectedRow();
				// 从表格模型中获得指定单元格的值
				Object oa = tableModel.getValueAt(selectedRow, 0);
				// 从表格模型中获得指定单元格的值
				Object ob = tableModel.getValueAt(selectedRow, 1);
				aTextField.setText(oa.toString());// 将值赋值给文本框
				bTextField.setText(ob.toString());// 将值赋值给文本框
			}
		});
		scrollPane.setViewportView(table);
		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.SOUTH);
		panel.add(new JLabel("A："));
		aTextField = new JTextField("A4", 10);
		panel.add(aTextField);
		panel.add(new JLabel("B："));
		bTextField = new JTextField("B4", 10);
		panel.add(bTextField);
		final JButton addButton = new JButton("添加");
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String[] rowValues = { aTextField.getText(),
						bTextField.getText() };// 创建表格行数组
				tableModel.addRow(rowValues);// 向表格模型中添加一行
				int rowCount = table.getRowCount() + 1;
				aTextField.setText("A" + rowCount);
				bTextField.setText("B" + rowCount);
			}
		});
		panel.add(addButton);
		final JButton updButton = new JButton("修改");
		updButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectedRow = table.getSelectedRow();// 获得被选中行的索引
				if (selectedRow != -1) {// 判断是否存在被选中行
					tableModel.setValueAt(aTextField.getText(),
							selectedRow, 0);// 修改表格模型当中的指定值
					tableModel.setValueAt(bTextField.getText(),
							selectedRow, 1);// 修改表格模型当中的指定值
				}
			}
		});
		panel.add(updButton);
		final JButton delButton = new JButton("删除");
		delButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectedRow = table.getSelectedRow();// 获得被选中行的索引
				if (selectedRow != -1)// 判断是否存在被选中行
					// 从表格模型当中删除指定行
					tableModel.removeRow(selectedRow);
			}
		});
		panel.add(delButton);
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="提供行标题栏的表格"><a href="#提供行标题栏的表格" class="headerlink" title="提供行标题栏的表格"></a>提供行标题栏的表格</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class MFixedColumnTable extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTable fixedColumnTable;// 固定列表格对象
	private FixedColumnTableModel fixedColumnTableModel;// 固定列表格模型对象
	private JTable floatingColumnTable;// 移动列表格对象
	// 移动列表格模型对象
	private FloatingColumnTableModel floatingColumnTableModel;
	private Vector&lt;String&gt; columnNameV;// 表格列名数组
	private Vector&lt;Vector&lt;Object&gt;&gt; tableValueV;// 表格数据数组
	private int fixedColumn = 1;// 固定列数量
	
public MFixedColumnTable(Vector&lt;String&gt; columnNameV,
		Vector&lt;Vector&lt;Object&gt;&gt; tableValueV, int fixedColumn) {
	super();
	setLayout(new BorderLayout());
	this.columnNameV = columnNameV;
	this.tableValueV = tableValueV;
	this.fixedColumn = fixedColumn;
	// 创建固定列表格模型对象
	fixedColumnTableModel = new FixedColumnTableModel();
	// 创建固定列表格对象
	fixedColumnTable = new JTable(fixedColumnTableModel);
	// 获得选择模型对象
	ListSelectionModel fixed = fixedColumnTable.getSelectionModel();
	// 选择模式为单选
	fixed.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	// 添加行被选中的事件监听器
	fixed.addListSelectionListener(new MListSelectionListener(true));
	// 创建可移动列表格模型对象
	floatingColumnTableModel = new FloatingColumnTableModel();
	// 创建可移动列表格对象
	floatingColumnTable = new JTable(floatingColumnTableModel);
	// 关闭表格的自动调整功能
	floatingColumnTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	ListSelectionModel floating = floatingColumnTable
			.getSelectionModel();// 获得选择模型对象
	// 选择模式为单选
	floating.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	// 添加行被选中的事件监听器
	MListSelectionListener listener = new MListSelectionListener(false);
	floating.addListSelectionListener(listener);
	JScrollPane scrollPane = new JScrollPane();// 创建一个滚动面版对象
	// 将固定列表格头放到滚动面版的左上方
	scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER,
			fixedColumnTable.getTableHeader());
	// 创建一个用来显示基础信息的视口对象
	JViewport viewport = new JViewport();
	viewport.setView(fixedColumnTable);// 将固定列表格添加到视口中
	// 设置视口的首选大小为固定列表格的首选大小
	viewport.setPreferredSize(fixedColumnTable.getPreferredSize());
	// 将视口添加到滚动面版的标题视口中
	 scrollPane.setRowHeaderView(viewport);
	// 将可移动表格添加到默认视口
	scrollPane.setViewportView(floatingColumnTable);
	add(scrollPane, BorderLayout.CENTER);
}
	
	private class FixedColumnTableModel extends AbstractTableModel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public int getColumnCount() {// 返回固定列的数量
			return fixedColumn;
		}
		
		public int getRowCount() {// 返回行数
			return tableValueV.size();
		}
		
		// 返回指定单元格的值
		public Object getValueAt(int rowIndex, int columnIndex) {
			return tableValueV.get(rowIndex).get(columnIndex);
		}
		
		@Override
		public String getColumnName(int columnIndex) {// 返回指定列的名称
			return columnNameV.get(columnIndex);
		}
	}
	
	private class FloatingColumnTableModel extends AbstractTableModel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public int getColumnCount() {// 返回可移动列的数量
			return columnNameV.size() - fixedColumn;// 需要扣除固定列的数量
		}
		
		public int getRowCount() {// 返回行数
			return tableValueV.size();
		}
		
		// 返回指定单元格的值
		public Object getValueAt(int rowIndex, int columnIndex) {
			// 需要为列索引加上固定列的数量
			return tableValueV.get(rowIndex)
					.get(columnIndex + fixedColumn);
		}
		
		@Override
		public String getColumnName(int columnIndex) {// 返回指定列的名称
			// 需要为列索引加上固定列的数量
			return columnNameV.get(columnIndex + fixedColumn);
		}
	}
	
	private class MListSelectionListener implements ListSelectionListener {
		boolean isFixedColumnTable = true; // 默认由选中固定列表格中的行触发
		
		public MListSelectionListener(boolean isFixedColumnTable) {
			this.isFixedColumnTable = isFixedColumnTable;
		}
		
		public void valueChanged(ListSelectionEvent e) {
			if (isFixedColumnTable) { // 由选中固定列表格中的行触发
				// 获得固定列表格中的选中行
				int row = fixedColumnTable.getSelectedRow();
				// 同时选中右侧可移动列表格中的相应行
				floatingColumnTable.setRowSelectionInterval(row, row);
			} else { // 由选中可移动列表格中的行触发
				// 获得可移动列表格中的选中行
				int row = floatingColumnTable.getSelectedRow();
				// 同时选中左侧固定列表格中的相应行
				fixedColumnTable.setRowSelectionInterval(row, row);
			}
		}
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.util.*;

import javax.swing.*;

public class ExampleFrame_07 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		try {
			ExampleFrame_07 frame = new ExampleFrame_07();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public ExampleFrame_07() {
		super();
		setTitle("提供行标题栏的表格");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Vector&lt;String&gt; columnNameV = new Vector&lt;&gt;();
		columnNameV.add("日期");
		for (int i = 1; i &lt; 21; i++) {
			columnNameV.add("商品" + i);
		}
		Vector&lt;Vector&lt;Object&gt;&gt; tableValueV = new Vector&lt;&gt;();
		for (int row = 1; row &lt; 31; row++) {
			Vector&lt;Object&gt; rowV = new Vector&lt;&gt;();
			rowV.add(row);
			for (int col = 0; col &lt; 20; col++) {
				rowV.add((int) (Math.random() * 1000));
			}
			tableValueV.add(rowV);
		}
		final MFixedColumnTable panel = new MFixedColumnTable(columnNameV,
				tableValueV, 1);
		getContentPane().add(panel, BorderLayout.CENTER);
		//
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="作业-1"><a href="#作业-1" class="headerlink" title="作业"></a>作业</h6><ul>
<li>选择日期的对话框</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;

public class Answer_2108 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Answer_2108 frame = new Answer_2108();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the frame
	 */
	public Answer_2108() {
		super();
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		final JPanel topPanel = new JPanel();
		getContentPane().add(topPanel, BorderLayout.NORTH);

		final JLabel topLabel = new JLabel();
		topLabel.setText("日期：");
		topPanel.add(topLabel);

		final MDateField topTreeComboBox = new MDateField();
		topPanel.add(topTreeComboBox);

		final JPanel bottomPanel = new JPanel();
		getContentPane().add(bottomPanel, BorderLayout.SOUTH);

		final JLabel bottomLabel = new JLabel();
		bottomLabel.setText("日期：");
		bottomPanel.add(bottomLabel);

		final MDateField bottomTreeComboBox = new MDateField();
		bottomPanel.add(bottomTreeComboBox);

		final JLabel label = new JLabel();
		label.setText("");
		getContentPane().add(label, BorderLayout.CENTER);
		//
	}

}




import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

public class MDateField extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField textField;

	public MDateField() {
		super();
		final FlowLayout flowLayout = new FlowLayout();
		flowLayout.setHgap(0);
		setLayout(flowLayout);

		textField = new JTextField();
		textField.setColumns(12);
		add(textField);

		final JButton button = new JButton();
		button.setText("...");
		button.setMargin(new Insets(0, 4, 0, 4));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Dimension preferredSize = textField.getPreferredSize();
				Point locationOnScreen = textField.getLocationOnScreen();
				int x = (int) locationOnScreen.getX();
				int y = (int) (locationOnScreen.getY() + preferredSize
						.getHeight());
				int width = 310;
				int height = 187;
				JRootPane rootPane = textField.getRootPane();
				Point rootPaneLocationOnScreen = rootPane.getLocationOnScreen();
				if (height &gt; rootPaneLocationOnScreen.getY()
						+ rootPane.getHeight() - y) {
					y = (int) (locationOnScreen.getY() - height);
				}
				ChooseDateDialog dialog = new ChooseDateDialog();
				dialog.setBounds(x, y, width, height);
				dialog.setVisible(true);
			}
		});
		add(button);
		//
	}

	class ChooseDateDialog extends JDialog {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		private int year;

		private int month;

		private int day;

		private int[] daysOfMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30,
				31, 30, 31 };

		private JTextField yTextField;

		private JTextField mTextField;

		private DefaultTableModel tableModel;

		public ChooseDateDialog() {
			super();
			setModal(true);
			setUndecorated(true);
			setBounds(100, 100, 310, 153);

			Calendar today = Calendar.getInstance();
			year = today.get(Calendar.YEAR);
			month = today.get(Calendar.MONTH) + 1;
			day = today.get(Calendar.DAY_OF_MONTH);
			if (year % 4 == 0) {
				if (year % 100 != 0 || year % 400 == 0)
					daysOfMonth[2] = 29;
				else
					daysOfMonth[2] = 28;
			} else {
				daysOfMonth[2] = 28;
			}

			final JPanel panel = new JPanel();
			panel.setLayout(new BorderLayout());
			panel.setBorder(new LineBorder(Color.black, 1, false));
			getContentPane().add(panel, BorderLayout.CENTER);

			final JPanel buttonPanel = new JPanel();
			panel.add(buttonPanel, BorderLayout.NORTH);

			final JButton pyButton = new JButton();
			pyButton.setText("&lt;&lt;");
			pyButton.setToolTipText("上一年");
			pyButton.setMargin(new Insets(0, 10, 0, 10));
			pyButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					yTextField.setText(--year + "");
					initTableModel();
				}
			});
			buttonPanel.add(pyButton);

			final JButton pmButton = new JButton();
			pmButton.setText("&lt;");
			pmButton.setToolTipText("上一月");
			pmButton.setMargin(new Insets(0, 12, 0, 12));
			pmButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					month--;
					if (month &lt; 1) {
						month = 12;
						yTextField.setText(--year + "");
					}
					mTextField.setText(month + "");
					initTableModel();
				}
			});
			buttonPanel.add(pmButton);

			yTextField = new JTextField();
			yTextField.setColumns(4);
			yTextField.setEditable(false);
			yTextField.setHorizontalAlignment(JTextField.CENTER);
			yTextField.setText(year + "");
			buttonPanel.add(yTextField);

			final JLabel yLabel = new JLabel();
			yLabel.setText("年");
			buttonPanel.add(yLabel);

			mTextField = new JTextField();
			mTextField.setColumns(2);
			mTextField.setEditable(false);
			mTextField.setHorizontalAlignment(JTextField.CENTER);
			mTextField.setText(month + "");
			buttonPanel.add(mTextField);

			final JLabel mLabel = new JLabel();
			mLabel.setText("月");
			buttonPanel.add(mLabel);

			final JButton nmButton = new JButton();
			nmButton.setText("&gt;");
			nmButton.setToolTipText("下一月");
			nmButton.setMargin(new Insets(0, 12, 0, 12));
			nmButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					month++;
					if (month &gt; 12) {
						month = 1;
						yTextField.setText(++year + "");
					}
					mTextField.setText(month + "");
					initTableModel();
				}
			});
			buttonPanel.add(nmButton);

			final JButton nyButton = new JButton();
			nyButton.setText("&gt;&gt;");
			nyButton.setToolTipText("下一年");
			nyButton.setMargin(new Insets(0, 12, 0, 12));
			nyButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					yTextField.setText(++year + "");
					initTableModel();
				}
			});
			buttonPanel.add(nyButton);

			final JScrollPane scrollPane = new JScrollPane();
			panel.add(scrollPane, BorderLayout.CENTER);

			tableModel = new DefaultTableModel(6, 7);
			String[] columnNames = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
					"星期六" };
			tableModel.setColumnIdentifiers(columnNames);
			initTableModel();

			final JTable table = new MTable(tableModel);
			table.setRowSelectionAllowed(false);
			table.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					String dayS = table.getValueAt(table.getSelectedRow(),
							table.getSelectedColumn()).toString();
					if (!dayS.startsWith("[")) {
						day = Integer.valueOf(dayS);
						textField.setText(getSelectedDate());
						dispose();
					}
				}
			});
			scrollPane.setViewportView(table);

			final JLabel label = new JLabel();
			label.setText(" ");
			panel.add(label, BorderLayout.WEST);

			final JLabel label_1 = new JLabel();
			label_1.setText(" ");
			panel.add(label_1, BorderLayout.EAST);

			final JPanel todayPanel = new JPanel();
			panel.add(todayPanel, BorderLayout.SOUTH);

			final JLabel label_2 = new JLabel();
			label_2.setText("今天：" + year + "-" + month + "-" + day + "  ");
			todayPanel.add(label_2);

			final JButton button = new JButton();
			button.setText("...");
			button.setMargin(new Insets(0, 12, 0, 12));
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					Calendar today = Calendar.getInstance();
					year = today.get(Calendar.YEAR);
					month = today.get(Calendar.MONTH) + 1;
					day = today.get(Calendar.DAY_OF_MONTH);
					if (year % 4 == 0) {
						if (year % 100 != 0 || year % 400 == 0)
							daysOfMonth[2] = 29;
						else
							daysOfMonth[2] = 28;
					} else {
						daysOfMonth[2] = 28;
					}
					yTextField.setText(year + "");
					mTextField.setText(month + "");
					initTableModel();
				}
			});
			todayPanel.add(button);

		}

		private void initTableModel() {
			DateFormat dateFormat = DateFormat.getDateInstance();
			try {
				dateFormat.parse(year + "-" + month + "-" + 1);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			Calendar theDay = dateFormat.getCalendar();
			int dayOfWeek = theDay.get(Calendar.DAY_OF_WEEK);
			for (int col = 0; col &lt; dayOfWeek - 1; col++) {
				int days = ((month - 1) &lt; 1 ? 31 : daysOfMonth[month - 1]);
				int day = days - ((dayOfWeek - 1) - 1 - col);
				tableModel.setValueAt("[ " + day + " ]", 0, col);
			}
			int day = 1;
			for (int col = dayOfWeek - 1; col &lt; 7; col++) {
				tableModel.setValueAt(day++, 0, col);
			}
			String s = "";
			String e = "";
			for (int row = 1; row &lt; 6; row++) {
				for (int col = 0; col &lt; 7; col++) {
					if (day &gt; daysOfMonth[month]) {
						s = "[ ";
						e = " ]";
						day = 1;
					}
					tableModel.setValueAt(s + day++ + e, row, col);
				}
			}
		}

		public String getSelectedDate() {
			return year + "-" + month + "-" + day;
		}

	}

	class MTable extends JTable {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public MTable() {
			super();
		}

		public MTable(DefaultTableModel tableModel) {
			super(tableModel);
		}

		// 表格列名信息
		@Override
		public JTableHeader getTableHeader() {
			// 获得表格头对象
			JTableHeader tableHeader = super.getTableHeader();
			tableHeader.setReorderingAllowed(false);// 设置表格列不可重排
			// 获得表格头的单元格对象
			DefaultTableCellRenderer defaultRenderer = (DefaultTableCellRenderer) tableHeader
					.getDefaultRenderer();
			// 设置单元格内容（即列名）居中显示
			defaultRenderer
					.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
			return tableHeader;
		}

		// 表格列值居中显示
		@Override
		public TableCellRenderer getDefaultRenderer(Class&lt;?&gt; columnClass) {
			// 获得除表格头部分的单元格对象
			DefaultTableCellRenderer defaultRenderer = (DefaultTableCellRenderer) super
					.getDefaultRenderer(columnClass);
			// 设置单元格内容居中显示
			defaultRenderer
					.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
			return defaultRenderer;
		}

		// 表格不可编辑
		@Override
		public boolean isCellEditable(int row, int column) {
			return false;
		}

		// 用来设置表格的选中行
		@Override
		public void setRowSelectionInterval(int fromRow, int toRow) {// 重构父类的方法
			super.setRowSelectionInterval(fromRow, toRow);
		}

		// 用来设置表格的唯一选中行
		public void setRowSelectionInterval(int row) {// 通过重载实现自己的方法
			setRowSelectionInterval(row, row);
		}

	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>以多列位行标题栏</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.util.*;

import javax.swing.*;

public class Answer_2109 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		try {
			Answer_2109 frame = new Answer_2109();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Answer_2109() {
		super();
		setTitle("提供行标题栏的表格");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Vector&lt;String&gt; columnNameV = new Vector&lt;&gt;();
		columnNameV.add("日期");
		columnNameV.add("营业额");// 添加一个日营业额列
		for (int i = 1; i &lt; 21; i++) {
			columnNameV.add("商品" + i);
		}
		Vector&lt;Vector&lt;Object&gt;&gt; tableValueV = new Vector&lt;&gt;();
		for (int row = 1; row &lt; 31; row++) {
			Vector&lt;Object&gt; rowV = new Vector&lt;&gt;();
			rowV.add(row);
			int sum = 0;// 日营业额
			for (int col = 0; col &lt; 20; col++) {
				int value = (int) (Math.random() * 1000);
				rowV.add(value);
				sum += value;// 累计日营业额
			}
			rowV.insertElementAt(sum, 1);// 插入日营业额数据
			tableValueV.add(rowV);
		}

		final MFixedColumnTable panel = new MFixedColumnTable(columnNameV,
				tableValueV, 2);// 修改固定列数量
		getContentPane().add(panel, BorderLayout.CENTER);
		//
	}
}





import java.awt.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class MFixedColumnTable extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTable fixedColumnTable;// 固定列表格对象

	private FixedColumnTableModel fixedColumnTableModel;// 固定列表格模型对象

	private JTable floatingColumnTable;// 移动列表格对象

	private FloatingColumnTableModel floatingColumnTableModel;// 移动列表格模型对象

	private Vector&lt;String&gt; columnNameV;// 表格列名数组

	private Vector&lt;Vector&lt;Object&gt;&gt; tableValueV;// 表格数据数组

	private int fixedColumn = 1;// 固定列数量

public MFixedColumnTable(Vector&lt;String&gt; columnNameV,
		Vector&lt;Vector&lt;Object&gt;&gt; tableValueV, int fixedColumn) {
	super();
	setLayout(new BorderLayout());

	this.columnNameV = columnNameV;
	this.tableValueV = tableValueV;
	this.fixedColumn = fixedColumn;

	fixedColumnTableModel = new FixedColumnTableModel();// 创建固定列表格模型对象

	fixedColumnTable = new JTable(fixedColumnTableModel);// 创建固定列表格对象
	ListSelectionModel fixed = fixedColumnTable.getSelectionModel();// 获得选择模型对象
	fixed.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);// 选择模式为单选
	fixed.addListSelectionListener(new MListSelectionListener(true));// 添加行被选中的事件监听器

	floatingColumnTableModel = new FloatingColumnTableModel();// 创建可移动列表格模型对象

	floatingColumnTable = new JTable(floatingColumnTableModel);// 创建可移动列表格对象
	floatingColumnTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);// 关闭表格的自动调整功能
	ListSelectionModel floating = floatingColumnTable.getSelectionModel();// 获得选择模型对象
	floating.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);// 选择模式为单选
	floating.addListSelectionListener(new MListSelectionListener(false));// 添加行被选中的事件监听器

	JScrollPane scrollPane = new JScrollPane();// 创建一个滚动面版对象
	scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColumnTable
			.getTableHeader()); // 将固定列表格头放到滚动面版的左上方

	JViewport viewport = new JViewport();// 创建一个用来显示基础信息的视口对象
	viewport.setView(fixedColumnTable);// 将固定列表格添加到视口中
	viewport.setPreferredSize(fixedColumnTable.getPreferredSize());// 设置视口的首选大小为固定列表格的首选大小
	scrollPane.setRowHeaderView(viewport);// 将视口添加到滚动面版的标题视口中

	scrollPane.setViewportView(floatingColumnTable);// 将可移动表格添加到默认视口

	add(scrollPane, BorderLayout.CENTER);
	//
}

	private class FixedColumnTableModel extends AbstractTableModel {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public int getColumnCount() {// 返回固定列的数量
			return fixedColumn;
		}

		public int getRowCount() {// 返回行数
			return tableValueV.size();
		}

		public Object getValueAt(int rowIndex, int columnIndex) {// 返回指定单元格的值
			return tableValueV.get(rowIndex).get(columnIndex);
		}

		@Override
		public String getColumnName(int columnIndex) {// 返回指定列的名称
			return columnNameV.get(columnIndex);
		}

	}

	private class FloatingColumnTableModel extends AbstractTableModel {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public int getColumnCount() {// 返回可移动列的数量
			return columnNameV.size() - fixedColumn;// 需要扣除固定列的数量
		}

		public int getRowCount() {// 返回行数
			return tableValueV.size();
		}

		public Object getValueAt(int rowIndex, int columnIndex) {// 返回指定单元格的值
			return tableValueV.get(rowIndex).get(columnIndex + fixedColumn);// 需要为列索引加上固定列的数量
		}

		@Override
		public String getColumnName(int columnIndex) {// 返回指定列的名称
			return columnNameV.get(columnIndex + fixedColumn);// 需要为列索引加上固定列的数量
		}

	}

	private class MListSelectionListener implements ListSelectionListener {
		boolean isFixedColumnTable = true; // 默认由选中固定列表格中的行触发

		public MListSelectionListener(boolean isFixedColumnTable) {
			this.isFixedColumnTable = isFixedColumnTable;
		}

		public void valueChanged(ListSelectionEvent e) {
			if (isFixedColumnTable) { // 由选中固定列表格中的行触发
				int row = fixedColumnTable.getSelectedRow(); // 获得固定列表格中的选中行
				floatingColumnTable.setRowSelectionInterval(row, row); // 同时选中右侧可移动列表格中的相应行
			} else { // 由选中可移动列表格中的行触发
				int row = floatingColumnTable.getSelectedRow(); // 获得可移动列表格中的选中行
				fixedColumnTable.setRowSelectionInterval(row, row); // 同时选中左侧固定列表格中的相应行
			}
		}
	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="11-树组件"><a href="#11-树组件" class="headerlink" title="11.树组件"></a>11.树组件</h4><h6 id="简单的树"><a href="#简单的树" class="headerlink" title="简单的树"></a>简单的树</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217195254.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;
import javax.swing.tree.*;

public class ExampleFrame_01 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_01 frame = new ExampleFrame_01();
		frame.setVisible(true);
	}
	
	public ExampleFrame_01() {
		super();
		setTitle("简单的树");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 创建根节点
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("根节点");
		// 创建一级节点
		DefaultMutableTreeNode nodeFirst = new DefaultMutableTreeNode(
				"一级子节点A");
		root.add(nodeFirst);// 将一级节点添加到根节点
		DefaultMutableTreeNode nodeSecond = new DefaultMutableTreeNode(
				"二级子节点", false);// 创建不允许有子节点的二级节点
		nodeFirst.add(nodeSecond);// 将二级节点添加到一级节点
		root.add(new DefaultMutableTreeNode("一级子节点B"));// 创建一级节点
		JTree treeRoot = new JTree(root);// 利用根节点直接创建树
		getContentPane().add(treeRoot, BorderLayout.WEST);
		// 利用根节点创建树模型，采用默认的判断方式
		DefaultTreeModel treeModelDefault = new DefaultTreeModel(root);
		// 利用树模型创建树
		JTree treeDefault = new JTree(treeModelDefault);
		getContentPane().add(treeDefault, BorderLayout.CENTER);
		// 利用根节点创建树模型，并采用非默认的判断方式
		DefaultTreeModel treeModelPointed = new DefaultTreeModel(root,
				true);
		JTree treePointed = new JTree(treeModelPointed);// 利用树模型创建树
		getContentPane().add(treePointed, BorderLayout.EAST);
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="处理选中节点事件"><a href="#处理选中节点事件" class="headerlink" title="处理选中节点事件"></a>处理选中节点事件</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217195320.png"></p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217195338.png"></p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217195352.png"></p>
<ul>
<li>监听器捕获选中树节点和取消选区树中节点的事件</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">aimport static javax.swing.tree.TreeSelectionModel.*;

import java.awt.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class ExampleFrame_02 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTree tree;
	
	public static void main(String args[]) {
		ExampleFrame_02 frame = new ExampleFrame_02();
		frame.setVisible(true);
	}
	
	public ExampleFrame_02() {
		super();
		setTitle("处理选中节点事件");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		DefaultMutableTreeNode root;// 创建树的跟节点
		root = new DefaultMutableTreeNode("本地磁盘（D：）");
		DefaultMutableTreeNode nodeA;// 创建树的一级子节点
		nodeA = new DefaultMutableTreeNode("图片");
		root.add(nodeA);// 将一级子结点添加到跟结点
		// 向一级子节点添加二级子节点
		nodeA.add(new DefaultMutableTreeNode("千山——世博园旅游"));
		DefaultMutableTreeNode nodeAB;// 创建树的二级子节点
		nodeAB = new DefaultMutableTreeNode("凤凰山——大鹿岛旅游");
		nodeA.add(nodeAB);// 将二级子节点添加到一级子节点
		// 向二级子节点添加叶子节点
		nodeAB.add(new DefaultMutableTreeNode("大浪淘沙.GIF", false));
		// 向二级子节点添加叶子节点
		nodeAB.add(new DefaultMutableTreeNode("辽阔的大海.JPG", false));
		// 向根节点添加一级子节点
		root.add(new DefaultMutableTreeNode("音乐"));
		DefaultTreeModel treeModel;// 通过树的根节点创建树模型
		treeModel = new DefaultTreeModel(root, true);
		tree = new JTree(treeModel);// 通过树模型创建树
		TreeSelectionModel treeSelectionModel;// 获得树的选择模型
		treeSelectionModel = tree.getSelectionModel();
		// 设置树的选择模式为连选
		treeSelectionModel.setSelectionMode(CONTIGUOUS_TREE_SELECTION);
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				if (!tree.isSelectionEmpty()) {// 查看是否存在被选中的节点
					// 获得所有被选中节点的路径
					TreePath[] selectionPaths = tree.getSelectionPaths();
					for (int i = 0; i &lt; selectionPaths.length; i++) {
						// 获得被选中节点的路径
						TreePath treePath = selectionPaths[i];
						// 以Object数组的形式返回该路径中所有节点的对象
						Object[] path = treePath.getPath();
						for (int j = 0; j &lt; path.length; j++) {
							DefaultMutableTreeNode node;// 获得节点
							node = (DefaultMutableTreeNode) path[j];
							String s = node.getUserObject()
									+ (j == (path.length - 1) ? "" : "--&gt;");
							System.out.print(s);// 输出节点标签
						}
						System.out.println();
					}
					System.out.println();
				}
			}
		});
		getContentPane().add(tree, BorderLayout.CENTER);
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="遍历树节点"><a href="#遍历树节点" class="headerlink" title="遍历树节点"></a>遍历树节点</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217195712.png"></p>
<ul>
<li>5中遍历方式</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.tree.*;

public class ExampleFrame_03 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private DefaultMutableTreeNode root;
	
	public static void main(String args[]) {
		ExampleFrame_03 frame = new ExampleFrame_03();
		frame.setVisible(true);
	}
	
	public ExampleFrame_03() {
		super();
		setTitle("遍历树节点");
		setBounds(100, 100, 290, 260);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		root = new DefaultMutableTreeNode("ROOT");
		DefaultMutableTreeNode nodeFirstA = new DefaultMutableTreeNode(
				"FirstA");
		nodeFirstA.add(new DefaultMutableTreeNode("SecondAA"));
		nodeFirstA.add(new DefaultMutableTreeNode("SecondAB"));
		root.add(nodeFirstA);
		DefaultMutableTreeNode nodeFirstB = new DefaultMutableTreeNode(
				"FirstB");
		root.add(nodeFirstB);
		DefaultMutableTreeNode nodeFirstC = new DefaultMutableTreeNode(
				"FirstC");
		nodeFirstC.add(new DefaultMutableTreeNode("SecondCA"));
		DefaultMutableTreeNode nedeSecondCB = new DefaultMutableTreeNode(
				"SecondCB");
		nedeSecondCB.add(new DefaultMutableTreeNode("SecondCBA"));
		nedeSecondCB.add(new DefaultMutableTreeNode("SecondCBB"));
		nodeFirstC.add(nedeSecondCB);
		nodeFirstC.add(new DefaultMutableTreeNode("SecondCC"));
		root.add(nodeFirstC);
		JTree tree = new JTree(root);
		getContentPane().add(tree, BorderLayout.CENTER);
		final JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(0, 1));
		getContentPane().add(panel, BorderLayout.EAST);
		final JButton button = new JButton("按前序遍历节点");
		button.addActionListener(new ButtonActionListener("按前序遍历"));
		panel.add(button);
		final JButton button_1 = new JButton("按后序遍历节点");
		button_1.addActionListener(new ButtonActionListener("按后序遍历"));
		panel.add(button_1);
		final JButton button_2 = new JButton("以广度优先遍历");
		button_2.addActionListener(new ButtonActionListener("以广度优先遍历"));
		panel.add(button_2);
		final JButton button_3 = new JButton("以深度优先遍历");
		button_3.addActionListener(new ButtonActionListener("以深度优先遍历"));
		panel.add(button_3);
		final JButton button_4 = new JButton("遍历直属子节点");
		button_4.addActionListener(new ButtonActionListener("遍历子节点"));
		panel.add(button_4);
	}
	
	private class ButtonActionListener implements ActionListener {
		
		private String mode;
		
		public ButtonActionListener(String mode) {
			this.mode = mode;
		}
		
		public void actionPerformed(ActionEvent e) {
			Enumeration&lt;?&gt; enumeration;// 声明节点枚举对象
			if (mode.equals("按前序遍历"))
				// 按前序遍历所有树节点
				enumeration = root.preorderEnumeration();
			else if (mode.equals("按后序遍历"))
				// 按后序遍历所有树节点
				enumeration = root.postorderEnumeration();
			else if (mode.equals("以广度优先遍历"))
				// 以广度优先遍历所有树节点
				enumeration = root.breadthFirstEnumeration();
			else if (mode.equals("以深度优先遍历"))
				// 以深度优先遍历所有树节点
				enumeration = root.depthFirstEnumeration();
			else
				enumeration = root.children(); // 遍历该节点的子节点
			while (enumeration.hasMoreElements()) {// 遍历节点枚举对象
				DefaultMutableTreeNode node;// 获得节点
				node = (DefaultMutableTreeNode) enumeration.nextElement();
				// 根据节点级别输出占位符
				for (int l = 0; l &lt; node.getLevel(); l++) {
					System.out.print("----");
				}
				System.out.println(node.getUserObject());// 输出节点标签
			}
			System.out.println();
			System.out.println();
		}
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="定制树"><a href="#定制树" class="headerlink" title="定制树"></a>定制树</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.util.*;

import javax.swing.*;
import javax.swing.tree.*;

public class ExampleFrame_04 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTree tree;
	public static void main(String args[]) {
		ExampleFrame_04 frame = new ExampleFrame_04();
		frame.setVisible(true);
	}
	public ExampleFrame_04() {
		super();
		setTitle("定制树");
		setBounds(100, 100, 200, 325);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		DefaultMutableTreeNode root;
		root = new DefaultMutableTreeNode("企业人事管理系统");
		DefaultMutableTreeNode nodeFirstA;
		nodeFirstA = new DefaultMutableTreeNode("人事管理");
		nodeFirstA.add(new DefaultMutableTreeNode("账套管理"));
		nodeFirstA.add(new DefaultMutableTreeNode("考勤管理"));
		nodeFirstA.add(new DefaultMutableTreeNode("奖惩管理"));
		nodeFirstA.add(new DefaultMutableTreeNode("培训管理"));
		root.add(nodeFirstA);
		DefaultMutableTreeNode nodeFirstB;
		nodeFirstB = new DefaultMutableTreeNode("待遇管理");
		nodeFirstB.add(new DefaultMutableTreeNode("帐套管理"));
		nodeFirstB.add(new DefaultMutableTreeNode("人员设置"));
		nodeFirstB.add(new DefaultMutableTreeNode("待遇报表"));
		root.add(nodeFirstB);
		DefaultMutableTreeNode nodeFirstC;
		nodeFirstC = new DefaultMutableTreeNode("系统维护");
		nodeFirstC.add(new DefaultMutableTreeNode("企业架构"));
		nodeFirstC.add(new DefaultMutableTreeNode("基本资料"));
		nodeFirstC.add(new DefaultMutableTreeNode("系统初始化"));
		root.add(nodeFirstC);
		tree = new JTree(root);
		tree.setRootVisible(false);// 不显示树的根节点
		tree.setRowHeight(20);// 树节点的行高为20像素
		tree.setFont(new Font("宋体", Font.BOLD, 14));// 设置树结点的字体
		// 节点间不采用连接线
		tree.putClientProperty("JTree.lineStyle", "None");
		DefaultTreeCellRenderer treeCellRenderer;// 获得树节点的绘制对象
		treeCellRenderer = (DefaultTreeCellRenderer) tree
				.getCellRenderer();
		treeCellRenderer.setLeafIcon(null);// 设置叶子节点不采用图标
		treeCellRenderer.setClosedIcon(null);// 设置节点折叠时不采用图标
		treeCellRenderer.setOpenIcon(null);// 设置节点展开时不采用图标
		Enumeration&lt;?&gt; enumeration; // 按前序遍历所有树节点
		enumeration = root.preorderEnumeration();
		while (enumeration.hasMoreElements()) {
			DefaultMutableTreeNode node;
			node = (DefaultMutableTreeNode) enumeration.nextElement();
			if (!node.isLeaf()) {// 判断是否为叶子节点
				// 创建该节点的路径
				TreePath path = new TreePath(node.getPath());
				tree.expandPath(path);// 如果不是则展开该节点
			}
		}
		getContentPane().add(tree, BorderLayout.CENTER);
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="维护树模型"><a href="#维护树模型" class="headerlink" title="维护树模型"></a>维护树模型</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217195847.png"></p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217195859.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.tree.*;

public class ExampleFrame_05 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTextField textField;
	
	private DefaultTreeModel treeModel;
	
	private JTree tree;
	
	public static void main(String args[]) {
		ExampleFrame_05 frame = new ExampleFrame_05();
		frame.setVisible(true);
	}
	
	public ExampleFrame_05() {
		super();
		setTitle("维护企业架构");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("倾诚爱家");
		
		DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("经理办公室");
		root.add(nodeA);
		
		DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("人事部");
		root.add(nodeB);
		
		DefaultMutableTreeNode nodeC = new DefaultMutableTreeNode("技术部");
		root.add(nodeC);
		nodeC.add(new DefaultMutableTreeNode("网络维护部"));
		nodeC.add(new DefaultMutableTreeNode("应用开发部"));
		
		DefaultMutableTreeNode nodeD = new DefaultMutableTreeNode("服务部");
		root.add(nodeD);
		nodeD.add(new DefaultMutableTreeNode("网络服务部"));
		nodeD.add(new DefaultMutableTreeNode("内勤开发部"));
		
		DefaultMutableTreeNode nodeE = new DefaultMutableTreeNode("推广部");
		root.add(nodeE);
		
		treeModel = new DefaultTreeModel(root, true);
		
		tree = new JTree(treeModel);
		tree.setSelectionPath(new TreePath(root));
		scrollPane.setViewportView(tree);
		
		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.SOUTH);
		
		final JLabel label = new JLabel();
		label.setText("名称：");
		panel.add(label);
		
		textField = new JTextField();
		textField.setColumns(8);
		textField.setText("测试");
		panel.add(textField);
		
		final JButton addButton = new JButton("添加");
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DefaultMutableTreeNode node = new DefaultMutableTreeNode(
						textField.getText());// 创建欲添加节点
				TreePath selectionPath = tree.getSelectionPath();// 获得选中的父节点路径
				DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) selectionPath
						.getLastPathComponent();// 获得选中的父节点
				treeModel.insertNodeInto(node, parentNode, parentNode
						.getChildCount());// 插入节点到所有子节点之后
				TreePath path = selectionPath.pathByAddingChild(node);// 获得新添加节点的路径
				if (!tree.isVisible(path))
					tree.makeVisible(path);// 如果该节点不可见则令其可见
			}
		});
		panel.add(addButton);
		
		final JButton updButton = new JButton("修改");
		updButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 获得选中的欲修改节点的路径
				TreePath selectionPath = tree.getSelectionPath();
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
						.getLastPathComponent();// 获得选中的欲修改节点
				node.setUserObject(textField.getText());// 修改节点的用户标签
				treeModel.nodeChanged(node);// 通知树模型该节点已经被修改
				tree.setSelectionPath(selectionPath);// 选中被修改的节点
			}
		});
		panel.add(updButton);
		
		final JButton delButton = new JButton("删除");
		delButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();// 获得选中的欲删除节点
				// 查看欲删除的节点是否为根节点，根节点不允许删除
				if (!node.isRoot()) {
					DefaultMutableTreeNode nextSelectedNode = node
							.getNextSibling();// 获得下一个兄弟节点，以备选中
					if (nextSelectedNode == null)// 查看是否存在兄弟节点
						nextSelectedNode = (DefaultMutableTreeNode) node
								.getParent();// 如果不存在则选中其父节点
					treeModel.removeNodeFromParent(node);// 删除节点
					tree.setSelectionPath(new TreePath(nextSelectedNode
							.getPath()));// 选中节点
				}
			}
		});
		panel.add(delButton);
		//
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="处理展开节点事件"><a href="#处理展开节点事件" class="headerlink" title="处理展开节点事件"></a>处理展开节点事件</h6><p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217200239.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class ExampleFrame_06 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTree tree;
	
	public static void main(String args[]) {
		ExampleFrame_06 frame = new ExampleFrame_06();
		frame.setVisible(true);
	}
	
	public ExampleFrame_06() {
		super();
		setTitle("处理展开节点事件");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("倾诚爱家");
		
		DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("经理办公室");
		root.add(nodeA);
		
		DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("人事部");
		root.add(nodeB);
		
		DefaultMutableTreeNode nodeC = new DefaultMutableTreeNode("技术部");
		root.add(nodeC);
		nodeC.add(new DefaultMutableTreeNode("网络维护部"));
		nodeC.add(new DefaultMutableTreeNode("应用开发部"));
		
		DefaultMutableTreeNode nodeD = new DefaultMutableTreeNode("服务部");
		root.add(nodeD);
		nodeD.add(new DefaultMutableTreeNode("网络服务部"));
		nodeD.add(new DefaultMutableTreeNode("内勤开发部"));
		
		DefaultMutableTreeNode nodeE = new DefaultMutableTreeNode("推广部");
		root.add(nodeE);
		
		tree = new JTree(root);
// 捕获树节点将要被展开或折叠的事件
tree.addTreeWillExpandListener(new TreeWillExpandListener() {
	// 树节点将要被折叠时触发
	public void treeWillCollapse(TreeExpansionEvent e) {
		TreePath path = e.getPath();// 获得将要被折叠节点的路径
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
				.getLastPathComponent();// 获得将要被折叠的节点
		System.out.println("节点“" + node + "”将要被折叠！");
	}
	
	// 树节点将要被展开时触发
	public void treeWillExpand(TreeExpansionEvent e) {
		TreePath path = e.getPath();// 获得将要被展开节点的路径
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
				.getLastPathComponent();// 获得将要被展开的节点
		System.out.println("节点“" + node + "”将要被展开！");
	}
});
// 捕获树节点已经被展开或折叠的事件
tree.addTreeExpansionListener(new TreeExpansionListener() {
	// 树节点已经折叠时触发
	public void treeCollapsed(TreeExpansionEvent e) {
		TreePath path = e.getPath();// 获得已经被折叠节点的路径
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
				.getLastPathComponent();// 获得已经被折叠的节点
		System.out.println("节点“" + node + "”已经被折叠！");
		System.out.println();
	}
	
	// 树节点已经被展开时触发
	public void treeExpanded(TreeExpansionEvent e) {
		TreePath path = e.getPath();// 获得已经被展开节点的路径
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
				.getLastPathComponent();// 获得已经被展开的节点
		System.out.println("节点“" + node + "”已经被展开！");
		System.out.println();
	}
});
		getContentPane().add(tree, BorderLayout.CENTER);
		//
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="作业-2"><a href="#作业-2" class="headerlink" title="作业"></a>作业</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.tree.*;

public class Answer_2207 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private DefaultTreeModel treeModel;
	
	private JTree tree;
	
	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Answer_2207 frame = new Answer_2207();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Create the frame
	 */
	public Answer_2207() {
		super();
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("倾诚爱家");
		
		DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("经理办公室");
		root.add(nodeA);
		
		DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("人事部");
		root.add(nodeB);
		
		DefaultMutableTreeNode nodeC = new DefaultMutableTreeNode("技术部");
		root.add(nodeC);
		nodeC.add(new DefaultMutableTreeNode("网络维护部"));
		nodeC.add(new DefaultMutableTreeNode("应用开发部"));
		
		DefaultMutableTreeNode nodeD = new DefaultMutableTreeNode("服务部");
		root.add(nodeD);
		nodeD.add(new DefaultMutableTreeNode("网络服务部"));
		nodeD.add(new DefaultMutableTreeNode("内勤开发部"));
		
		DefaultMutableTreeNode nodeE = new DefaultMutableTreeNode("推广部");
		root.add(nodeE);
		
		treeModel = new DefaultTreeModel(root, true);
		
		tree = new JTree(treeModel);
		tree.setSelectionRow(0);
		getContentPane().add(tree, BorderLayout.CENTER);
		
		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.SOUTH);
		
		final JButton addButton = new JButton("添加");
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				TreePath selectionPath = tree.getSelectionPath();
				int pathCount = selectionPath.getPathCount();// 获得选中节点的级别
				had: if (pathCount == 3) {// 选中的为3级节点
					JOptionPane.showMessageDialog(null,
							"很抱歉，在该级部门下不能再包含子部门！", "友情提示",
							JOptionPane.WARNING_MESSAGE);
				} else {// 选中的为1级或2级节点
					String infos[] = { "请输入部门名称：", "添加新部门", "请输入部门名称！" };
					String newName = getName(infos);// 获得新部门的名称
					if (newName != null) {// 创建新部门
						DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) selectionPath
								.getLastPathComponent();// 获得选中部门节点对象
						int childCount = parentNode.getChildCount();// 获得该部门包含子部门的个数
						for (int i = 0; i &lt; childCount; i++) {// 查看新创建的部门是否已经存在
							TreeNode childNode = parentNode.getChildAt(i);
							if (childNode.toString().equals(newName)) {
								JOptionPane.showMessageDialog(null,
										"该部门已经存在！", "友情提示",
										JOptionPane.WARNING_MESSAGE);
								break had;// 已经存在，跳出到指定位置
							}
						}
						DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(
								newName);// 创建新部门节点对象
						treeModel.insertNodeInto(childNode, parentNode,
								childCount);// 将新部门节点插入到选中部门节点的最后
						tree.expandPath(selectionPath);// 展开选中部门节点
					}
				}
			}
		});
		panel.add(addButton);
		
		final JButton updButton = new JButton("修改");
		updButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				TreePath selectionPath = tree.getSelectionPath();
				String newName = null;
				if (selectionPath.getPathCount() == 1) {// 修改公司名称
					int i = JOptionPane.showConfirmDialog(null,
							"确定要修改贵公司的名称？", "友情提示",
							JOptionPane.YES_NO_OPTION);// 弹出提示框
					if (i == 0) {// 修改（单击“是”按钮）
						String infos[] = { "请输入贵公司的新名称：", "修改公司名称",
								"请输入贵公司的新名称！" };
						newName = getName(infos);// 获得修改后的名称
					}
				} else {// 修改部门名称
					String infos[] = { "请输入部门的新名称：", "修改部门名称",
							"请输入部门的新名称！" };
					newName = getName(infos);// 获得修改后的名称
					if (newName != null) {
						DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
								.getLastPathComponent();
						DefaultMutableTreeNode nodeParent = (DefaultMutableTreeNode) node
								.getParent();
						for (int i = 0; i &lt; nodeParent.getChildCount(); i++) {
							DefaultMutableTreeNode nodeSibling = (DefaultMutableTreeNode) nodeParent
									.getChildAt(i);
							if (!nodeSibling.equals(node)) {
								if (nodeSibling.getUserObject().toString()
										.equals(newName)) {
									JOptionPane.showMessageDialog(null,
											"该部门已经存在！", "友情提示",
											JOptionPane.WARNING_MESSAGE);
									newName = null;
								}
							}
						}
					}
				}
				if (newName != null) {
					DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) selectionPath
							.getLastPathComponent();// 获得选中节点对象
					treeNode.setUserObject(newName);// 修改节点名称
					treeModel.reload();// 刷新树结构
					tree.setSelectionPath(selectionPath);// 设置节点为选中状态
				}
			}
		});
		panel.add(updButton);
		
		final JButton delButton = new JButton("删除");
		delButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();// 获得选中的欲删除节点
				if (!node.isRoot()) {// 查看欲删除的节点是否为根节点，根节点不允许删除
					DefaultMutableTreeNode nextSelectedNode = node
							.getNextSibling();// 获得下一个兄弟节点，以备选中
					if (nextSelectedNode == null)// 查看是否存在兄弟节点
						nextSelectedNode = (DefaultMutableTreeNode) node
								.getParent();// 如果不存在则选中其父节点
					treeModel.removeNodeFromParent(node);// 删除节点
					tree.setSelectionPath(new TreePath(nextSelectedNode
							.getPath()));// 选中节点
				}
			}
		});
		panel.add(delButton);
		//
	}
	
	private String getName(String infos[]) {
		String newName = "";
		while (newName != null &amp;&amp; newName.length() == 0) {
			newName = JOptionPane.showInputDialog(null, infos[0],
					infos[1], JOptionPane.INFORMATION_MESSAGE);
			if (newName != null &amp;&amp; newName.length() == 0) {
				JOptionPane.showMessageDialog(null, infos[2], "友情提示",
						JOptionPane.INFORMATION_MESSAGE);
			}
		}
		return newName;
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">
import java.awt.*;

import javax.swing.*;
import javax.swing.tree.*;

public class Answer_2208 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Answer_2208 frame = new Answer_2208();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Create the frame
	 */
	public Answer_2208() {
		super();
		setTitle("支持树状结构的下拉菜单");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("明日科技");
		DefaultMutableTreeNode aNode2 = new DefaultMutableTreeNode("人事部");
		root.add(aNode2);
		DefaultMutableTreeNode bNode2 = new DefaultMutableTreeNode("开发部");
		root.add(bNode2);
		DefaultMutableTreeNode aNode3 = new DefaultMutableTreeNode("VB");
		bNode2.add(aNode3);
		DefaultMutableTreeNode bNode3 = new DefaultMutableTreeNode("VC");
		bNode2.add(bNode3);
		
		final JPanel topPanel = new JPanel();
		getContentPane().add(topPanel, BorderLayout.NORTH);
		
		final JLabel topLabel = new JLabel();
		topLabel.setText("部门：");
		topPanel.add(topLabel);
		
		final MTreeComboBox topTreeComboBox = new MTreeComboBox(root, 10,
				1.2);
		topPanel.add(topTreeComboBox);
		
		final JPanel bottomPanel = new JPanel();
		getContentPane().add(bottomPanel, BorderLayout.SOUTH);
		
		final JLabel bottomLabel = new JLabel();
		bottomLabel.setText("部门：");
		bottomPanel.add(bottomLabel);
		
		final MTreeComboBox bottomTreeComboBox = new MTreeComboBox(root,
				20, 1.2);
		bottomPanel.add(bottomTreeComboBox);
		
		final JLabel label = new JLabel();
		label.setText("");
		getContentPane().add(label, BorderLayout.CENTER);
		//
	}
	
}





import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class MTreeComboBox extends JPanel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTextField textField;
	
	private DefaultMutableTreeNode root;
	
	public MTreeComboBox(DefaultMutableTreeNode root, int column,
			final double percentOfHeightInWidth) {
		super();
		final FlowLayout flowLayout = new FlowLayout();
		flowLayout.setHgap(0);
		setLayout(flowLayout);
		
		this.root = root;
		
		textField = new JTextField();
		textField.setColumns(column);
		add(textField);
		
		final JButton button = new JButton();
		button.setText("...");
		button.setMargin(new Insets(0, 4, 0, 4));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Dimension preferredSize = textField.getPreferredSize();
				Point locationOnScreen = textField.getLocationOnScreen();
				int x = (int) locationOnScreen.getX();
				int y = (int) (locationOnScreen.getY() + preferredSize
						.getHeight());
				int width = (int) preferredSize.getWidth();
				int height = (int) (width * percentOfHeightInWidth);
				JRootPane rootPane = textField.getRootPane();
				Point rootPaneLocationOnScreen = rootPane
						.getLocationOnScreen();
				if (height &gt; rootPaneLocationOnScreen.getY()
						+ rootPane.getHeight() - y) {
					y = (int) (locationOnScreen.getY() - height);
				}
				ListDialog listDialog = new ListDialog();
				listDialog.setBounds(x, y, width, height);
				listDialog.setVisible(true);
			}
		});
		add(button);
		//
	}
	
	private class ListDialog extends JDialog {
		
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private JTree tree;
		
		public ListDialog() {
			super();
			setModal(true);
			setUndecorated(true);
			
			final JScrollPane scrollPane = new JScrollPane();
			getContentPane().add(scrollPane, BorderLayout.CENTER);
			
			tree = new JTree(root);
			DefaultTreeCellRenderer treeCellRenderer = new DefaultTreeCellRenderer();
			treeCellRenderer.setClosedIcon(null);
			treeCellRenderer.setOpenIcon(null);
			treeCellRenderer.setLeafIcon(null);
			tree.setCellRenderer(treeCellRenderer);
			tree.addTreeSelectionListener(new TreeSelectionListener() {
				public void valueChanged(TreeSelectionEvent e) {
					textField.setText(tree.getLastSelectedPathComponent()
							.toString());
					dispose();
				}
			});
			scrollPane.setViewportView(tree);
			//
		}
		
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="12-其他高级组件"><a href="#12-其他高级组件" class="headerlink" title="12.其他高级组件"></a>12.其他高级组件</h4><h6 id="高级组件面板"><a href="#高级组件面板" class="headerlink" title="高级组件面板"></a>高级组件面板</h6><ul>
<li>分割面板</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;

import javax.swing.*;
public class ExampleFrame_01 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static void main(String args[]) {
		ExampleFrame_01 frame = new ExampleFrame_01();
		frame.setVisible(true);
	}
	public ExampleFrame_01() {
		super();
		setTitle("分割面板");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 创建一个水平方向的分割面板
		final JSplitPane hSplitPane = new JSplitPane();
		// 分隔条左侧的宽度为40像素
		hSplitPane.setDividerLocation(40);
		// 添加到指定区域
		getContentPane().add(hSplitPane, BorderLayout.CENTER);
		// 在水平面板左侧添加一个标签组件
		hSplitPane.setLeftComponent(new JLabel("      1"));
		// 创建一个垂直方向的分割面板
		final JSplitPane vSplitPane = new JSplitPane(
				JSplitPane.VERTICAL_SPLIT);
		// 分隔条上方的高度为30像素
		vSplitPane.setDividerLocation(30);
		vSplitPane.setDividerSize(8);// 分隔条的宽度为8像素
		vSplitPane.setOneTouchExpandable(true);// 提供UI小部件
		// 在调整分隔条位置时面板的重绘方式为连续绘制
		vSplitPane.setContinuousLayout(true);
		hSplitPane.setRightComponent(vSplitPane);// 添加到水平面板的右侧
		// 在垂直面板上方添加一个标签组件
		vSplitPane.setLeftComponent(new JLabel("      2"));
		// 在垂直面板下方添加一个标签组件
		vSplitPane.setRightComponent(new JLabel("      3"));
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="选项卡面板"><a href="#选项卡面板" class="headerlink" title="选项卡面板"></a>选项卡面板</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.net.*;

import javax.swing.*;
import javax.swing.event.*;

public class ExampleFrame_02 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_02 frame = new ExampleFrame_02();
		frame.setVisible(true);
	}
	
	public ExampleFrame_02() {
		super();
		getContentPane().setFocusCycleRoot(true);
		setTitle("选项卡面板");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		final JTabbedPane tabbedPane = new JTabbedPane();
		// 设置选项卡标签的布局方式
		tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		tabbedPane.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				// 获得被选中选项卡的索引
				int selectedIndex = tabbedPane.getSelectedIndex();
				// 获得指定索引的选项卡标签
				String title = tabbedPane.getTitleAt(selectedIndex);
				System.out.println(title);
			}
		});
		getContentPane().add(tabbedPane, BorderLayout.CENTER);
		URL resource = ExampleFrame_02.class.getResource("/tab.JPG");
		ImageIcon imageIcon = new ImageIcon(resource);
		final JLabel tabLabelA = new JLabel();
		tabLabelA.setText("选项卡A");
		// 将标签组件添加到选项卡中
		tabbedPane.addTab("选项卡A", imageIcon, tabLabelA, "点击查看选项卡A");
		final JLabel tabLabelB = new JLabel();
		tabLabelB.setText("选项卡B");
		tabbedPane.addTab("选项卡B", imageIcon, tabLabelB, "点击查看选项卡B");
		final JLabel tabLabelC = new JLabel();
		tabLabelC.setText("选项卡C");
		tabbedPane.addTab("选项卡C", imageIcon, tabLabelC, "点击查看选项卡C");
		tabbedPane.setSelectedIndex(2); // 设置索引为2的选项卡被选中
		tabbedPane.setEnabledAt(0, false); // 设置索引为0的选项卡不可用
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="桌面面板和内部窗体"><a href="#桌面面板和内部窗体" class="headerlink" title="桌面面板和内部窗体"></a>桌面面板和内部窗体</h6><ul>
<li>JDesktopPane</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.net.*;

import javax.swing.*;

public class ExampleFrame_03 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_03 frame = new ExampleFrame_03();
		frame.setVisible(true);
	}
	
	public ExampleFrame_03() {
		super();
		setTitle("为桌面面板添加背景图片");
		setBounds(100, 100, 570, 430);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 创建一个桌面面板对象
		final JDesktopPane desktopPane = new JDesktopPane();
		getContentPane().add(desktopPane, BorderLayout.CENTER);
		final JLabel backLabel = new JLabel(); // 创建一个标签组件对象
		// 获得背景图片的路径
		URL resource = this.getClass().getResource("/back.JPG");
		ImageIcon icon = new ImageIcon(resource); // 创建背景图片对象
		backLabel.setIcon(icon); // 令标签组件显示背景图片
		// 设置组件的显示位置及大小
		backLabel.setBounds(0, 0, icon.getIconWidth(), icon
				.getIconHeight());
		// 将标签组件添加到指定索引位置
		desktopPane.add(backLabel, new Integer(Integer.MIN_VALUE));
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>JInternalFrame类</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.net.*;

import javax.swing.*;

public class ExampleFrame_03 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JDesktopPane desktopPane = null;// 定义一个桌面面板对象
	InternalFrame pInFrame = null;// 定义一个人事管理内部窗体对象
	InternalFrame rInFrame = null;// 定义一个账套管理内部窗体对象
	InternalFrame tInFrame = null;// 定义一个待遇报表内部窗体对象
	public static void main(String args[]) {
		ExampleFrame_03 frame = new ExampleFrame_03();
		frame.setVisible(true);
	}
	public ExampleFrame_03() {
		super();
		setTitle("企业人事管理系统");
		setBounds(100, 100, 570, 470);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 创建桌面面板
		desktopPane = new JDesktopPane();// 创建桌面面板对象
		// 设置内部窗体的拖动模式
		desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
		getContentPane().add(desktopPane, BorderLayout.CENTER);
		// 为桌面面板添加背景图片
		final JLabel backLabel = new JLabel(); // 创建一个标签组件对象
		// 获得背景图片的路径
		URL resource = this.getClass().getResource("/back.JPG");
		ImageIcon icon = new ImageIcon(resource); // 创建背景图片对象
		backLabel.setIcon(icon); // 令标签组件显示背景图片
		// 设置组件的显示位置及大小
		backLabel.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight());
		// 将标签组件添加到指定索引位置
		desktopPane.add(backLabel, new Integer(Integer.MIN_VALUE));
		// 添加按钮
		final JPanel panel = new JPanel();
		final FlowLayout flowLayout = new FlowLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		panel.setLayout(flowLayout);
		getContentPane().add(panel, BorderLayout.NORTH);
		
		final JButton personnelButton = new JButton();
		personnelButton.setText("人事管理");
		personnelButton
				.addActionListener(new BAListener(pInFrame, "人事管理"));
		panel.add(personnelButton);
		
		final JButton reckoningButton = new JButton();
		reckoningButton.setText("账套管理");
		reckoningButton
				.addActionListener(new BAListener(rInFrame, "账套管理"));
		panel.add(reckoningButton);
		
		final JButton treatmentButton = new JButton();
		treatmentButton.setText("待遇报表");
		treatmentButton
				.addActionListener(new BAListener(tInFrame, "待遇报表"));
		panel.add(treatmentButton);
	}
	
	private class BAListener implements ActionListener {
		InternalFrame inFrame;
		String title;
		public BAListener(InternalFrame inFrame, String title) {
			this.inFrame = inFrame;
			this.title = title;
		}
		public void actionPerformed(ActionEvent e) {
			if (inFrame == null || inFrame.isClosed()) {
				// 获得桌面面板中的所有内部窗体
				JInternalFrame[] allFrames = desktopPane.getAllFrames();
				// 获得桌面面板中拥有内部窗体的数量
				int titleBarHight = 30 * allFrames.length;
				int x = 10 + titleBarHight, y = x;// 设置窗体的显示位置
				int width = 250, height = 180;// 设置窗体的大小
				inFrame = new InternalFrame(title);// 创建指定标题的内部窗体
				// 设置窗体的显示位置及大小
				inFrame.setBounds(x, y, width, height);
				inFrame.setVisible(true);// 设置窗体可见
				desktopPane.add(inFrame);// 将窗体添加到桌面面板中
			}
			try {
				inFrame.setSelected(true);// 选中窗体
			} catch (PropertyVetoException propertyVetoE) {
				propertyVetoE.printStackTrace();
			}
		}
	}
	private class InternalFrame extends JInternalFrame {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public InternalFrame(String title) {
			super();
			setTitle(title);// 设置内部窗体的标题
			setResizable(true);// 设置允许自由调整大小
			setClosable(true);// 设置提供关闭按钮
			setIconifiable(true);// 设置提供图标化按钮
			setMaximizable(true);// 设置提供最大化按钮
			// 获得图片的路径
			URL resource = this.getClass().getResource("/in_frame.png"); 
			ImageIcon icon = new ImageIcon(resource); // 创建图片对象
			setFrameIcon(icon); // 设置窗体图标
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="菜单"><a href="#菜单" class="headerlink" title="菜单"></a>菜单</h6><ul>
<li>创建菜单栏</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.event.*;

import javax.swing.*;

public class ExampleFrame_05 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_05 frame = new ExampleFrame_05();
		frame.setVisible(true);
	}
	
	public ExampleFrame_05() {
		super();
		setTitle("创建菜单栏");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JMenuBar menuBar = new JMenuBar();// 创建菜单栏对象
		setJMenuBar(menuBar);// 将菜单栏对象添加到窗体的菜单栏中
		
		JMenu menu = new JMenu("菜单名称");// 创建菜单对象
		menuBar.add(menu);// 将菜单对象添加到菜单栏对象中
		
		JMenuItem menuItem = new JMenuItem("菜单项名称");// 创建菜单项对象
		menuItem.addActionListener(new ItemListener());// 为菜单项添加事件监听器
		menu.add(menuItem);// 将菜单项对象添加到菜单对象中
		
		JMenu sonMenu = new JMenu("子菜单名称");// 创建菜单的子菜单对象
		menu.add(sonMenu);// 将子菜单对象添加到上级菜单对象中
		
		JMenuItem sonMenuItem = new JMenuItem("子菜单项名称");// 创建子菜单的菜单项对象
		sonMenuItem.addActionListener(new ItemListener());// 为菜单项添加事件监听器
		sonMenu.add(sonMenuItem);// 将子菜单的菜单项对象添加到子菜单对象中
		
		JMenu menu2 = new JMenu("菜单名称2");// 创建菜单对象
		menuBar.add(menu2);// 将菜单对象添加到菜单栏对象中
		
		JMenuItem menuItem2 = new JMenuItem("菜单项名称2");// 创建菜单项对象
		menuItem2.addActionListener(new ItemListener());// 为菜单项添加事件监听器
		menu2.add(menuItem2);// 将菜单项对象添加到菜单对象中
		
		JMenu sonMenu2 = new JMenu("子菜单名称2");// 创建菜单的子菜单对象
		menu2.add(sonMenu2);// 将子菜单对象添加到上级菜单对象中
		
		JMenuItem sonMenuItem2 = new JMenuItem("子菜单项名称2");// 创建子菜单的菜单项对象
		sonMenuItem2.addActionListener(new ItemListener());// 为菜单项添加事件监听器
		sonMenu2.add(sonMenuItem2);// 将子菜单的菜单项对象添加到子菜单对象中
		//
	}
	
	private class ItemListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JMenuItem menuItem = (JMenuItem) e.getSource();
			System.out.println("您单击的是菜单项：" + menuItem.getText());
		}
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>弹出式菜单</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class ExampleFrame_06 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_06 frame = new ExampleFrame_06();
		frame.setVisible(true);
	}
	
	public ExampleFrame_06() {
		super();
		setTitle("创建弹出式菜单");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JLabel label = new JLabel();
		label.setText("                请在窗口中单击鼠标右键！");
		getContentPane().add(label, BorderLayout.CENTER);
		
		final JPopupMenu popupMenu = new JPopupMenu();// 创建弹出式菜单对象
		// 为窗体的顶层容器添加鼠标事件监听器
		getContentPane().addMouseListener(new MouseAdapter() {
			// 鼠标按键被释放时触发该方法
			public void mouseReleased(MouseEvent e) {
				// 判断此次鼠标事件是否为该组件的弹出菜单触发事件
				// 如果是则在释放鼠标的位置弹出菜单
				if (e.isPopupTrigger())
					popupMenu.show(e.getComponent(), e.getX(), e.getY());
			}
		});
		
		final JMenuItem cutItem = new JMenuItem("剪切");
		cutItem.addActionListener(new ItemListener());
		popupMenu.add(cutItem);
		
		final JMenuItem copyItem = new JMenuItem("复制");
		copyItem.addActionListener(new ItemListener());
		popupMenu.add(copyItem);
		
		final JMenuItem pastItem = new JMenuItem("粘贴");
		pastItem.addActionListener(new ItemListener());
		popupMenu.add(pastItem);
		
		final JMenu editMenu = new JMenu("编辑");
		popupMenu.add(editMenu);
		
		final JMenuItem readItem = new JMenuItem("只读");
		readItem.addActionListener(new ItemListener());
		editMenu.add(readItem);
		
		final JMenuItem writeItem = new JMenuItem("可写");
		writeItem.addActionListener(new ItemListener());
		editMenu.add(writeItem);
		
		final JMenu fontMenu = new JMenu("字体");
		editMenu.add(fontMenu);
		
		final JMenuItem boldfacedItem = new JMenuItem("加粗");
		boldfacedItem.addActionListener(new ItemListener());
		fontMenu.add(boldfacedItem);
		
		final JMenuItem italicItem = new JMenuItem("斜体");
		italicItem.addActionListener(new ItemListener());
		fontMenu.add(italicItem);
		//
	}
	
	private class ItemListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JMenuItem menuItem = (JMenuItem) e.getSource();
			System.out.println("您单击的是菜单项：" + menuItem.getText());
		}
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>定制个性化菜单栏</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import static java.awt.event.InputEvent.*;
import static java.awt.event.KeyEvent.*;

import java.awt.event.*;
import java.net.*;

import javax.swing.*;

public class ExampleFrame_07 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	final ButtonGroup buttonGroup = new ButtonGroup();
	
	public static void main(String args[]) {
		ExampleFrame_07 frame = new ExampleFrame_07();
		frame.setVisible(true);
	}
	
	public ExampleFrame_07() {
		super();
		setBounds(100, 100, 500, 375);
		setTitle("订制个性化菜单");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		final JMenu fileMenu = new JMenu("文件（F）");// 创建“文件”菜单
		fileMenu.setMnemonic('F');// 设置快捷键
		menuBar.add(fileMenu);// 添加到菜单栏
		final JMenuItem newItem = new JMenuItem("新建（N）");// 创建菜单项
		newItem.setMnemonic('N');// 设置快捷键
		// 设置加速器为“Ctrl+N”
		newItem.setAccelerator(KeyStroke.getKeyStroke(VK_N, CTRL_MASK));
		newItem.addActionListener(new ItemListener());// 添加动作监听器
		fileMenu.add(newItem);// 添加到“文件”菜单
		final JMenu openMenu = new JMenu("打开（O）");// 创建“打开”子菜单
		openMenu.setMnemonic('O');// 设置快捷键
		fileMenu.add(openMenu);// 添加到“文件”菜单
		// 创建子菜单项
		final JMenuItem openNewItem = new JMenuItem("未打开过的（N）");
		openNewItem.setMnemonic('N');// 设置快捷键
		// 设置加速器为“Ctrl+Alt+N”
		openNewItem.setAccelerator(KeyStroke.getKeyStroke(VK_N, CTRL_MASK
				| ALT_MASK));
		openNewItem.addActionListener(new ItemListener());// 添加动作监听器
		openMenu.add(openNewItem);// 添加到“打开”子菜单
		// 创建子菜单项
		final JMenuItem openClosedItem = new JMenuItem("刚打开过的（C）");
		openClosedItem.setMnemonic('C');// 设置快捷键
		// 设置加速器
		openClosedItem.setAccelerator(KeyStroke.getKeyStroke(VK_C,
				CTRL_MASK | ALT_MASK));
		openClosedItem.setEnabled(false);// 禁用菜单项
		// 添加动作监听器
		openClosedItem.addActionListener(new ItemListener());
		openMenu.add(openClosedItem);// 添加到“打开”子菜单
		fileMenu.addSeparator();// 添加分隔线
		
		final JMenuItem saveItem = new JMenuItem();
		saveItem.setText("保存（S）");
		saveItem.setMnemonic('S');
		saveItem.setAccelerator(KeyStroke.getKeyStroke(VK_S, CTRL_MASK));
		saveItem.addActionListener(new ItemListener());
		fileMenu.add(saveItem);
		
		fileMenu.addSeparator();
		
		final JMenuItem exitItem = new JMenuItem();
		exitItem.setText("退出（E）");
		exitItem.setMnemonic('E');
		exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
				InputEvent.CTRL_MASK));
		exitItem.addActionListener(new ItemListener());
		fileMenu.add(exitItem);
		
		final JMenu editMenu = new JMenu();
		editMenu.setText("编辑（E）");
		editMenu.setMnemonic('E');
		menuBar.add(editMenu);
		
		URL resource = this.getClass().getResource("/img.JPG");
		ImageIcon icon = new ImageIcon(resource);
		
		final JMenuItem cutItem = new JMenuItem();
		cutItem.setIcon(icon);
		cutItem.setText("剪切（T）");
		cutItem.setMnemonic('T');
		cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
				InputEvent.CTRL_MASK));
		cutItem.addActionListener(new ItemListener());
		editMenu.add(cutItem);
		
		final JMenuItem copyItem = new JMenuItem();
		copyItem.setIcon(icon);
		copyItem.setText("复制（C）");
		copyItem.setMnemonic('C');
		copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
				InputEvent.CTRL_MASK));
		copyItem.addActionListener(new ItemListener());
		editMenu.add(copyItem);
		
		final JMenuItem pastItem = new JMenuItem();
		pastItem.setIcon(icon);
		pastItem.setText("粘贴（P）");
		pastItem.setMnemonic('P');
		pastItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
				InputEvent.CTRL_MASK));
		pastItem.addActionListener(new ItemListener());
		editMenu.add(pastItem);
		
		editMenu.addSeparator();
		editMenu.insertSeparator(2);
		
		final JMenu fontMenu = new JMenu("字体（F）");// 创建“字体”子菜单
		fontMenu.setIcon(icon);// 设置菜单图标
		fontMenu.setMnemonic('F');// 设置快捷键
		editMenu.add(fontMenu);// 添加到“编辑”菜单
		final JCheckBoxMenuItem bCheckBoxItem = new JCheckBoxMenuItem(
				"加粗（B）");// 创建复选框菜单项
		bCheckBoxItem.setMnemonic('B');// 设置快捷键
		bCheckBoxItem.setAccelerator(KeyStroke.getKeyStroke(VK_B,
				CTRL_MASK | ALT_MASK)); // 设置加速器为“Ctrl+Alt+B”
		bCheckBoxItem.addActionListener(new ItemListener()); // 添加动作监听器
		fontMenu.add(bCheckBoxItem);// 添加到“字体”子菜单
		final JCheckBoxMenuItem iCheckBoxItem = new JCheckBoxMenuItem(
				"斜体（I）");// 创建复选框菜单项
		iCheckBoxItem.setMnemonic('I');// 设置快捷键
		iCheckBoxItem.setAccelerator(KeyStroke.getKeyStroke(VK_I,
				CTRL_MASK | ALT_MASK)); // 设置加速器为“Ctrl+Alt+I”
		iCheckBoxItem.addActionListener(new ItemListener()); // 添加动作监听器
		fontMenu.add(iCheckBoxItem);// 添加到“字体”子菜单
		
		editMenu.addSeparator();
		
		final JMenu attributeMenu = new JMenu("属性（A）");// 创建“属性”子菜单
		attributeMenu.setIcon(icon);// 设置菜单图标
		attributeMenu.setMnemonic('A');// 设置快捷键
		editMenu.add(attributeMenu);// 添加到“编辑”菜单
		final JRadioButtonMenuItem rRadioButtonItem = new JRadioButtonMenuItem(
				"只读（R）");// 创建单选按钮菜单项
		rRadioButtonItem.setMnemonic('R');// 设置快捷键
		rRadioButtonItem.setAccelerator(KeyStroke.getKeyStroke(VK_R,
				CTRL_MASK | ALT_MASK));// 设置加速器为“Ctrl+Alt+R”
		buttonGroup.add(rRadioButtonItem);// 添加到按钮组
		rRadioButtonItem.setSelected(true);// 设置为被选中
		rRadioButtonItem.addActionListener(new ItemListener());// 添加动作监听器
		attributeMenu.add(rRadioButtonItem);// 添加到“属性”子菜单
		final JRadioButtonMenuItem eRadioButtonItem = new JRadioButtonMenuItem(
				"编辑（E）");// 创建单选按钮菜单项
		eRadioButtonItem.setMnemonic('E');// 设置快捷键
		eRadioButtonItem.setAccelerator(KeyStroke.getKeyStroke(VK_E,
				CTRL_MASK | ALT_MASK));// 设置加速器为“Ctrl+Alt+E”
		buttonGroup.add(eRadioButtonItem);// 添加到按钮组
		eRadioButtonItem.addActionListener(new ItemListener());// 添加动作监听器
		attributeMenu.add(eRadioButtonItem);// 添加到“属性”子菜单
		
		final JMenu helpMenu = new JMenu("帮助（H）", false);
		helpMenu.setText("帮助（H）");
		helpMenu.setMnemonic('H');
		menuBar.add(helpMenu);
		
		final JMenuItem aboutItem = new JMenuItem();
		aboutItem.setText("关于（A）");
		aboutItem.setMnemonic('A');
		aboutItem.addActionListener(new ItemListener());
		helpMenu.add(aboutItem);
		//
	}
	
	private class ItemListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JMenuItem menuItem = (JMenuItem) e.getSource();
			System.out.println("您单击的是菜单项：" + menuItem.getText());
		}
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>工具栏</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class ExampleFrame_08 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_08 frame = new ExampleFrame_08();
		frame.setVisible(true);
	}
	
	public ExampleFrame_08() {
		super();
		setTitle("使用工具栏");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		final JToolBar toolBar = new JToolBar("工具栏");// 创建工具栏对象
		toolBar.setFloatable(false);// 设置为不允许拖动
		getContentPane().add(toolBar, BorderLayout.NORTH);// 添加到网格布局的上方
		final JButton newButton = new JButton("新建");// 创建按钮对象
		newButton.addActionListener(new ButtonListener());// 添加动作事件监听器
		toolBar.add(newButton);// 添加到工具栏中
		toolBar.addSeparator();// 添加默认大小的分隔符
		final JButton saveButton = new JButton("保存");// 创建按钮对象
		saveButton.addActionListener(new ButtonListener());// 添加动作事件监听器
		toolBar.add(saveButton);// 添加到工具栏中
		toolBar.addSeparator(new Dimension(20, 0));// 添加指定大小的分隔符
		final JButton exitButton = new JButton("退出");// 创建按钮对象
		exitButton.addActionListener(new ButtonListener());// 添加动作事件监听器
		toolBar.add(exitButton);// 添加到工具栏中
	}
	
	private class ButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JButton button = (JButton) e.getSource();
			System.out.println("您单击的是：" + button.getText());
		}
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="文件选择器"><a href="#文件选择器" class="headerlink" title="文件选择器"></a>文件选择器</h6><ul>
<li>文件选择对话框</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

public class ExampleFrame_09 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField textField;
	
	public static void main(String args[]) {
		ExampleFrame_09 frame = new ExampleFrame_09();
		frame.setVisible(true);
	}
	
	public ExampleFrame_09() {
		super();
		setTitle("文件选择对话框");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);
		
		final JLabel label = new JLabel();
		label.setText("文件：");
		panel.add(label);
		
		textField = new JTextField();
		textField.setColumns(20);
		panel.add(textField);
		
		final JButton button = new JButton();
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();// 创建文件选择对话框
				// 显示文件选择对话框
				int i = fileChooser.showOpenDialog(getContentPane());
				// 判断用户单击的是否为“打开”按钮
				if (i == JFileChooser.APPROVE_OPTION) {
					// 获得选中的文件对象
					File selectedFile = fileChooser.getSelectedFile();
					// 显示选中文件的名称
					textField.setText(selectedFile.getName());
				}
			}
		});
		button.setText("上传");
		panel.add(button);
		//
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>使用文件过滤器</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;

public class ExampleFrame_10 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_10 frame = new ExampleFrame_10();
		frame.setVisible(true);
	}
	
	public ExampleFrame_10() {
		super();
		setTitle("选择照片对话框");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JLabel label = new JLabel("&lt;双击选择照片&gt;", SwingConstants.CENTER);
		label.addMouseListener(new MouseAdapter() {
			JFileChooser fileChooser;
			{
				// 创建文件选择对话框
				fileChooser = new JFileChooser();
				// 设置文件过滤器，只列出JPG或GIF格式的图片
				FileFilter filter = new FileNameExtensionFilter(
						"图像文件（JPG/GIF）", "JPG", "JPEG", "GIF");
				fileChooser.setFileFilter(filter);
			}
			
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					// 显示文件选择对话框
					int i = fileChooser.showOpenDialog(getContentPane());
					// 判断用户单击的是否为“打开”按钮
					if (i == JFileChooser.APPROVE_OPTION) {
						// 获得选中的图片对象
						File selectedFile = fileChooser.getSelectedFile();
						label.setIcon(new ImageIcon(selectedFile
								.getAbsolutePath()));// 将图片显示到标签上
						label.setText(null);
					}
				}
			}
		});
		getContentPane().add(label, BorderLayout.CENTER);
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="进度条"><a href="#进度条" class="headerlink" title="进度条"></a>进度条</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class ExampleFrame_11 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_11 frame = new ExampleFrame_11();
		frame.setVisible(true);
	}
	
	public ExampleFrame_11() {
		super();
		getContentPane().setLayout(new GridBagLayout());
		setTitle("使用进度条");
		setBounds(100, 100, 500, 375);
		setBounds(100, 100, 266, 132);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JLabel label = new JLabel();
		label.setForeground(new Color(255, 0, 0));
		label.setFont(new Font("", Font.BOLD, 16));
		label.setText("欢迎使用在线升级功能！");
		final GridBagConstraints gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridy = 0;
		gridBagConstraints.gridx = 0;
		getContentPane().add(label, gridBagConstraints);
		
		final JProgressBar progressBar = new JProgressBar();// 创建进度条对象
		progressBar.setStringPainted(true);// 设置显示提示信息
		progressBar.setIndeterminate(true);// 设置采用不确定进度条
		progressBar.setString("升级进行中......");// 设置提示信息
		final GridBagConstraints gridBagConstraints_1 = new GridBagConstraints();
		gridBagConstraints_1.insets = new Insets(5, 0, 0, 0);
		gridBagConstraints_1.gridy = 1;
		gridBagConstraints_1.gridx = 0;
		getContentPane().add(progressBar, gridBagConstraints_1);
		
		final JButton button = new JButton();
		button.setText("完成");
		button.setEnabled(false);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		final GridBagConstraints gridBagConstraints_2 = new GridBagConstraints();
		gridBagConstraints_2.insets = new Insets(5, 0, 0, 0);
		gridBagConstraints_2.gridy = 2;
		gridBagConstraints_2.gridx = 1;
		getContentPane().add(button, gridBagConstraints_2);
		new Progress(progressBar, button).start();// 利用线程模拟一个在线升级任务
	}
	
	class Progress extends Thread {// 利用线程模拟一个在线升级任务
		private final int[] progressValue = { 6, 18, 27, 39, 51, 66, 81,
				100 };// 模拟任务完成百分比
		private JProgressBar progressBar;// 进度条对象
		private JButton button;// 完成按钮对象
		
		public Progress(JProgressBar progressBar, JButton button) {
			this.progressBar = progressBar;
			this.button = button;
		}
		
		public void run() {
			// 通过循环更新任务完成百分比
			for (int i = 0; i &lt; progressValue.length; i++) {
				try {
					Thread.sleep(1000);// 令线程休眠1秒
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				progressBar.setValue(progressValue[i]);// 设置任务完成百分比
			}
			progressBar.setIndeterminate(false);// 设置采用确定进度条
			progressBar.setString("升级完成！");// 设置提示信息
			button.setEnabled(true);// 设置按钮可用
		}
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="系统托盘"><a href="#系统托盘" class="headerlink" title="系统托盘"></a>系统托盘</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.net.*;

import javax.swing.*;

public class ExampleFrame_12 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_12 frame = new ExampleFrame_12();
		frame.setVisible(true);
		try {
			frame.addIconToTray();
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}
	
	public ExampleFrame_12() {
		super();
		setTitle("使用系统托盘");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JLabel label = new JLabel();
		label.setForeground(new Color(0, 128, 0));
		label.setFont(new Font("", Font.BOLD, 16));
		label.setHorizontalAlignment(SwingConstants.CENTER);
		label.setText("请查看系统托盘中的变化！");
		getContentPane().add(label, BorderLayout.CENTER);
		//
	}
	
	public void addIconToTray() throws AWTException {
		if (SystemTray.isSupported()) {// 判断系统是否支持系统托盘功能
			URL resource = this.getClass().getResource("/img.JPG");// 获得图片路径
			ImageIcon icon = new ImageIcon(resource);// 创建图片对象
			PopupMenu popupMenu = new PopupMenu();// 创建弹出菜单对象
			MenuItem item = new MenuItem("退出");// 创建“退出”菜单项目对象
			// 为菜单项目添加动作监听器
			item.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.exit(0);// 退出系统
				}
			});
			popupMenu.add(item);// 将“退出”菜单项目添加到弹出菜单中
			TrayIcon trayIcon = new TrayIcon(icon.getImage(), "使用系统托盘",
					popupMenu);// 创建托盘图片对象
			// 获得系统托盘对象
			SystemTray systemTray = SystemTray.getSystemTray();
			systemTray.add(trayIcon);// 将托盘图片添加到系统托盘中
		}
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="桌面集成控件"><a href="#桌面集成控件" class="headerlink" title="桌面集成控件"></a>桌面集成控件</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

import javax.swing.*;

public class ExampleFrame_13 extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ExampleFrame_13 frame = new ExampleFrame_13();
		frame.setVisible(true);
	}
	
	public ExampleFrame_13() {
		super();
		setTitle("使用桌面集成控件");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);
		
		final JButton dickButton = new JButton();
		dickButton.setText("打开编程词典网");
		dickButton.addActionListener(new ButtonListener(1));
		panel.add(dickButton);
		
		final JButton noteButton = new JButton();
		noteButton.setText("打开记事本");
		noteButton.addActionListener(new ButtonListener(2));
		panel.add(noteButton);
		
		final JButton wordButton = new JButton();
		wordButton.setText("打开Word");
		wordButton.addActionListener(new ButtonListener(0));
		panel.add(wordButton);
		//
	}
	
	private class ButtonListener implements ActionListener {
		
		int index;
		
		public ButtonListener(int index) {
			this.index = index;
		}
		
		public void actionPerformed(ActionEvent e) {
			try {
if (Desktop.isDesktopSupported()) { // 判断系统是否提供了对该类的支持
	Desktop desktop = Desktop.getDesktop();// 获得该类的对象
	switch (index) {
		case 1:
			// 判断是否支持“浏览”动作
			if (desktop.isSupported(Desktop.Action.BROWSE))
				desktop.browse(new URI(
						"http://www.mrbccd.com"));// 浏览网站
			break;
		case 2:
			// 判断是否支持“编辑”动作
			if (desktop.isSupported(Desktop.Action.EDIT))
				desktop.edit(new File("src/new.txt"));// 编辑记事本
			break;
		default:
			// 判断是否支持“打开”动作
			if (desktop.isSupported(Desktop.Action.OPEN))
				desktop.open(new File("src/new.doc"));// 打开Word
	}
}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="作业-3"><a href="#作业-3" class="headerlink" title="作业"></a>作业</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.net.*;

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;

public class Answer_2314 extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private ButtonGroup showInfoButtonGroup = new ButtonGroup();

	private ButtonGroup leaveInfoButtonGroup = new ButtonGroup();

	private ButtonGroup leave_2InfoButtonGroup = new ButtonGroup();

	private JTable table;

	private JTextField textField_1;

	private JTextArea textArea;

	private JTree tree;

	private JTextField textField;

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Answer_2314 dialog = new Answer_2314();
			dialog.addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					System.exit(0);
				}
			});
			dialog.setVisible(true);
			dialog.addIconToTray();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Add the SystemTray
	 */
	public void addIconToTray() throws AWTException {
		if (SystemTray.isSupported()) {// 判断系统是否支持系统托盘功能

			URL resource = this.getClass().getResource("/img.JPG");// 获得图片路径
			ImageIcon icon = new ImageIcon(resource);// 创建图片对象

			PopupMenu popupMenu = new PopupMenu();// 创建弹出菜单对象
			MenuItem item = new MenuItem("退出");// 创建“退出”菜单项目对象
			item.addActionListener(new ActionListener() {// 为菜单项目添加动作监听器
						public void actionPerformed(ActionEvent e) {
							System.exit(0);// 退出系统
						}
					});
			popupMenu.add(item);// 将“退出”菜单项目添加到弹出菜单中

			TrayIcon trayIcon = new TrayIcon(icon.getImage(), "我的QQ", popupMenu);// 创建托盘图片对象

			SystemTray systemTray = SystemTray.getSystemTray();// 获得系统托盘对象
			systemTray.add(trayIcon);// 将托盘图片添加到系统托盘中
		}
	}

	/**
	 * Create the dialog
	 */
	public Answer_2314() {
		super();
		setTitle("我的QQ");
		setBounds(100, 100, 270, 570);

		final JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		final JMenu menu = new JMenu();
		menu.setText("文件（F）");
		menu.setMnemonic('F');
		menuBar.add(menu);

		final JMenuItem menuItem = new JMenuItem();
		menuItem.setText("更改用户");
		menu.add(menuItem);

		menu.addSeparator();

		final JMenu menu_3 = new JMenu();
		menu_3.setText("我的状态");
		menu.add(menu_3);

		final JMenuItem menuItem_1 = new JMenuItem();
		menuItem_1.setText("上线");
		menu_3.add(menuItem_1);

		final JMenu menu_7 = new JMenu();
		menu_7.setText("离开");
		menu_3.add(menu_7);

		final JRadioButtonMenuItem radioButtonMenuItem_2 = new JRadioButtonMenuItem();
		leaveInfoButtonGroup.add(radioButtonMenuItem_2);
		radioButtonMenuItem_2.setText("现在忙！");
		menu_7.add(radioButtonMenuItem_2);

		final JRadioButtonMenuItem radioButtonMenuItem_3 = new JRadioButtonMenuItem();
		leaveInfoButtonGroup.add(radioButtonMenuItem_3);
		radioButtonMenuItem_3.setText("马上回来！");
		menu_7.add(radioButtonMenuItem_3);

		final JRadioButtonMenuItem radioButtonMenuItem_4 = new JRadioButtonMenuItem();
		leaveInfoButtonGroup.add(radioButtonMenuItem_4);
		radioButtonMenuItem_4.setText("正在参加会议！");
		menu_7.add(radioButtonMenuItem_4);

		final JRadioButtonMenuItem radioButtonMenuItem_5 = new JRadioButtonMenuItem();
		leaveInfoButtonGroup.add(radioButtonMenuItem_5);
		radioButtonMenuItem_5.setText("休息中，请勿打扰！");
		menu_7.add(radioButtonMenuItem_5);

		menu_7.addSeparator();

		final JRadioButtonMenuItem radioButtonMenuItem_6 = new JRadioButtonMenuItem();
		radioButtonMenuItem_6.setSelected(true);
		leaveInfoButtonGroup.add(radioButtonMenuItem_6);
		radioButtonMenuItem_6.setText("不回复消息");
		menu_7.add(radioButtonMenuItem_6);

		menu_7.addSeparator();

		final JMenuItem menuItem_22 = new JMenuItem();
		menuItem_22.setText("自定义...");
		menu_7.add(menuItem_22);

		final JMenuItem menuItem_6 = new JMenuItem();
		menuItem_6.setText("离线");
		menu_3.add(menuItem_6);

		menu.addSeparator();

		final JMenuItem menuItem_2 = new JMenuItem();
		menuItem_2.setText("个人设置");
		menu.add(menuItem_2);

		final JMenuItem menuItem_3 = new JMenuItem();
		menuItem_3.setText("系统设置");
		menu.add(menuItem_3);

		menu.addSeparator();

		final JMenuItem menuItem_4 = new JMenuItem();
		menuItem_4.setText("退出");
		menu.add(menuItem_4);

		final JMenu menu_1 = new JMenu();
		menu_1.setText("联系人（P）");
		menu_1.setMnemonic('P');
		menuBar.add(menu_1);

		final JMenuItem menuItem_7 = new JMenuItem();
		menuItem_7.setText("查找联系人");
		menu_1.add(menuItem_7);

		menu_1.addSeparator();

		final JMenu menu_4 = new JMenu();
		menu_4.setText("管理联系人");
		menu_1.add(menu_4);

		final JMenuItem menuItem_8 = new JMenuItem();
		menuItem_8.setText("添加联系人");
		menu_4.add(menuItem_8);

		final JMenuItem menuItem_9 = new JMenuItem();
		menuItem_9.setText("删除联系人");
		menu_4.add(menuItem_9);

		final JMenu menu_5 = new JMenu();
		menu_5.setText("管理自定义组");
		menu_1.add(menu_5);

		final JMenuItem menuItem_10 = new JMenuItem();
		menuItem_10.setText("添加自定义组");
		menu_5.add(menuItem_10);

		final JMenuItem menuItem_11 = new JMenuItem();
		menuItem_11.setText("删除自定义组");
		menu_5.add(menuItem_11);

		menu_5.addSeparator();

		final JMenuItem menuItem_12 = new JMenuItem();
		menuItem_12.setText("设置自定义组");
		menu_5.add(menuItem_12);

		menu_1.addSeparator();

		final JMenu menu_6 = new JMenu();
		menu_6.setText("显示方式");
		menu_1.add(menu_6);

		final JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem();
		checkBoxMenuItem.setState(true);
		checkBoxMenuItem.setText("显示账号");
		menu_6.add(checkBoxMenuItem);

		final JCheckBoxMenuItem checkBoxMenuItem_1 = new JCheckBoxMenuItem();
		checkBoxMenuItem_1.setSelected(true);
		checkBoxMenuItem_1.setText("显示姓名");
		menu_6.add(checkBoxMenuItem_1);

		menu_6.addSeparator();

		final JRadioButtonMenuItem radioButtonMenuItem = new JRadioButtonMenuItem();
		radioButtonMenuItem.setSelected(true);
		showInfoButtonGroup.add(radioButtonMenuItem);
		radioButtonMenuItem.setText("显示所有联系人");
		menu_6.add(radioButtonMenuItem);

		final JRadioButtonMenuItem radioButtonMenuItem_1 = new JRadioButtonMenuItem();
		showInfoButtonGroup.add(radioButtonMenuItem_1);
		radioButtonMenuItem_1.setText("只显示在线联系人");
		menu_6.add(radioButtonMenuItem_1);

		final JMenu menu_2 = new JMenu();
		menu_2.setText("操作（O）");
		menu_2.setMnemonic('O');
		menuBar.add(menu_2);

		final JMenuItem menuItem_13 = new JMenuItem();
		menuItem_13.setText("发送消息");
		menu_2.add(menuItem_13);

		final JMenuItem menuItem_14 = new JMenuItem();
		menuItem_14.setText("发送文件");
		menu_2.add(menuItem_14);

		menu_2.addSeparator();

		final JMenuItem menuItem_15 = new JMenuItem();
		menuItem_15.setText("查看消息记录");
		menu_2.add(menuItem_15);

		final JMenuItem menuItem_16 = new JMenuItem();
		menuItem_16.setText("查看离线消息");
		menu_2.add(menuItem_16);

		final JMenuItem menuItem_17 = new JMenuItem();
		menuItem_17.setText("查看未读消息");
		menu_2.add(menuItem_17);

		final JMenu menu_9 = new JMenu();
		menu_9.setText("帮助（H）");
		menu_9.setMnemonic('H');
		menuBar.add(menu_9);

		final JMenuItem menuItem_18 = new JMenuItem();
		menuItem_18.setText("帮助");
		menu_9.add(menuItem_18);

		menu_9.addSeparator();

		final JMenuItem menuItem_19 = new JMenuItem();
		menuItem_19.setText("关于");
		menu_9.add(menuItem_19);

		final JPanel panel = new JPanel();
		final FlowLayout flowLayout = new FlowLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		panel.setLayout(flowLayout);
		getContentPane().add(panel, BorderLayout.NORTH);

		final JLabel label = new JLabel();
		label
				.setIcon(new ImageIcon(this.getClass().getResource(
						"/head.gif")));
		panel.add(label);

		final JPanel panel_1 = new JPanel();
		panel_1.setLayout(new GridLayout(0, 1));
		panel.add(panel_1);

		final JPanel panel_2 = new JPanel();
		final FlowLayout flowLayout_1 = new FlowLayout();
		flowLayout_1.setAlignment(FlowLayout.LEFT);
		panel_2.setLayout(flowLayout_1);
		panel_1.add(panel_2);

		final JLabel label_1 = new JLabel();
		label_1.setText("17833518");
		panel_2.add(label_1);

		final JButton button = new MButton();
		button.setText("在线 ▼");
		panel_2.add(button);

		final JPopupMenu popupMenu = new JPopupMenu();
		addPopup(button, popupMenu);

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				popupMenu.show(button, button.getX(), button.getY());
			}
		});

		//
		final JMenuItem menuItem_111 = new JMenuItem();
		menuItem_111.setText("上线");
		popupMenu.add(menuItem_111);

		final JMenu menu_117 = new JMenu();
		menu_117.setText("离开");
		popupMenu.add(menu_117);

		final JRadioButtonMenuItem radioButtonMenuItem_112 = new JRadioButtonMenuItem();
		leave_2InfoButtonGroup.add(radioButtonMenuItem_112);
		radioButtonMenuItem_112.setText("现在忙！");
		menu_117.add(radioButtonMenuItem_112);

		final JRadioButtonMenuItem radioButtonMenuItem_113 = new JRadioButtonMenuItem();
		leave_2InfoButtonGroup.add(radioButtonMenuItem_113);
		radioButtonMenuItem_113.setText("马上回来！");
		menu_117.add(radioButtonMenuItem_113);

		final JRadioButtonMenuItem radioButtonMenuItem_114 = new JRadioButtonMenuItem();
		leave_2InfoButtonGroup.add(radioButtonMenuItem_114);
		radioButtonMenuItem_114.setText("正在参加会议！");
		menu_117.add(radioButtonMenuItem_114);

		final JRadioButtonMenuItem radioButtonMenuItem_115 = new JRadioButtonMenuItem();
		leave_2InfoButtonGroup.add(radioButtonMenuItem_115);
		radioButtonMenuItem_115.setText("休息中，请勿打扰！");
		menu_117.add(radioButtonMenuItem_115);

		menu_117.addSeparator();

		final JRadioButtonMenuItem radioButtonMenuItem_116 = new JRadioButtonMenuItem();
		radioButtonMenuItem_116.setSelected(true);
		leave_2InfoButtonGroup.add(radioButtonMenuItem_116);
		radioButtonMenuItem_116.setText("不回复消息");
		menu_117.add(radioButtonMenuItem_116);

		menu_117.addSeparator();

		final JMenuItem menuItem_1122 = new JMenuItem();
		menuItem_1122.setText("自定义...");
		menu_117.add(menuItem_1122);

		final JMenuItem menuItem_116 = new JMenuItem();
		menuItem_116.setText("离线");
		popupMenu.add(menuItem_116);
		//

		final JPanel panel_3 = new JPanel();
		panel_1.add(panel_3);

		final JButton button_1 = new MButton();
		button_1.setText("离线消息");
		panel_3.add(button_1);

		final JButton button_2 = new MButton();
		button_2.setText("未读消息");
		panel_3.add(button_2);

		final JPanel panel_4 = new JPanel();
		panel_4.setLayout(new BorderLayout());
		getContentPane().add(panel_4, BorderLayout.CENTER);

		final JToolBar toolBar = new JToolBar();
		panel_4.add(toolBar, BorderLayout.NORTH);

		textField = new JTextField();
		textField.setText("&lt;可按账号、姓名或拼音进行查找&gt;");
		textField.addFocusListener(new FocusListener() {
			public void focusGained(FocusEvent e) {
				textField.setText(null);
			}

			public void focusLost(FocusEvent e) {
				textField.setText("&lt;可按账号、姓名或拼音进行查找&gt;");
			}
		});
		toolBar.add(textField);

		final JButton button_3 = new JButton();
		button_3.setText("查找");
		toolBar.add(button_3);

		final JSplitPane splitPane = new JSplitPane();
		splitPane.setDividerLocation(300);
		splitPane.setOneTouchExpandable(true);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		panel_4.add(splitPane, BorderLayout.CENTER);

		final JTabbedPane tabbedPane = new JTabbedPane();
		tabbedPane.setTabPlacement(SwingConstants.LEFT);
		splitPane.setLeftComponent(tabbedPane);

		final JScrollPane scrollPane = new JScrollPane();
		tabbedPane.addTab("&lt;html&gt;&lt;br&gt;联&lt;br&gt;系&lt;br&gt;人&lt;br&gt;&lt;br&gt;&lt;/html&gt;", null,
				scrollPane, null);

		DefaultMutableTreeNode root = new DefaultMutableTreeNode("");
		String[] types = { "联系人", "我的好友", "黑名单" };
		String[][] personnels = { { "A", "B", "C", "D", "E", "F" },
				{ "G", "H", "I", "J", "K", "L" },
				{ "M", "N", "O", "P", "Q", "R" } };
		for (int i = 0; i &lt; 3; i++) {
			DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(
					types[i]);
			for (int j = 0; j &lt; 6; j++) {
				typeNode
						.add(new DefaultMutableTreeNode(personnels[i][j], false));
			}
			root.add(typeNode);
		}

		tree = new JTree(root, true);
		tree.setRootVisible(false);
		scrollPane.setViewportView(tree);

		final JSplitPane splitPane_1 = new JSplitPane();
		splitPane_1.setOneTouchExpandable(true);
		splitPane_1.setDividerLocation(200);
		splitPane_1.setOrientation(JSplitPane.VERTICAL_SPLIT);
		tabbedPane.addTab("&lt;html&gt;&lt;br&gt;备&lt;br&gt;忘&lt;br&gt;录&lt;br&gt;&lt;br&gt;&lt;/html&gt;", null,
				splitPane_1, null);

		final JPanel panel_7 = new JPanel();
		panel_7.setLayout(new BorderLayout());
		splitPane_1.setLeftComponent(panel_7);

		final JPanel panel_8 = new JPanel();
		panel_7.add(panel_8, BorderLayout.NORTH);

		final JButton button_6 = new JButton();
		button_6.setText("新建");
		panel_8.add(button_6);

		final JButton button_7 = new JButton();
		button_7.setText("修改");
		panel_8.add(button_7);

		final JButton button_8 = new JButton();
		button_8.setText("删除");
		panel_8.add(button_8);

		final JScrollPane scrollPane_1 = new JScrollPane();
		panel_7.add(scrollPane_1, BorderLayout.CENTER);

		String[] columnNames = { "时间", "主题" };
		DefaultTableModel tableModel = new DefaultTableModel(null, columnNames);

		table = new JTable(tableModel);
		scrollPane_1.setViewportView(table);

		final JPanel panel_6 = new JPanel();
		panel_6.setLayout(new BorderLayout());
		splitPane_1.setRightComponent(panel_6);

		textField_1 = new JTextField();
		panel_6.add(textField_1, BorderLayout.NORTH);

		final JScrollPane scrollPane_2 = new JScrollPane();
		panel_6.add(scrollPane_2, BorderLayout.CENTER);

		textArea = new JTextArea();
		scrollPane_2.setViewportView(textArea);

		final JPanel panel_5 = new JPanel();
		panel_5.setLayout(new BoxLayout(panel_5, BoxLayout.Y_AXIS));
		splitPane.setRightComponent(panel_5);

		final JButton button_4 = new MButton();
		button_4.setText("查找联系人");
		panel_5.add(button_4);

		final JButton button_5 = new MButton();
		button_5.setText("查看消息记录");
		panel_5.add(button_5);

		final JLabel label_2 = new JLabel();
		label_2.setHorizontalAlignment(SwingConstants.RIGHT);
		label_2.setText("| 本地 ");
		getContentPane().add(label_2, BorderLayout.SOUTH);
		//
	}

	private class MButton extends JButton {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public MButton() {
			setMargin(new Insets(0, 0, 0, 0));
			setFocusPainted(false);
			setBorderPainted(false);
			setContentAreaFilled(false);
		}
	}

	private static void addPopup(final Component component,
			final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger())
					showMenu(e);
			}

			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger())
					showMenu(e);
			}

			private void showMenu(MouseEvent e) {
				popup
						.show(e.getComponent(), component.getX(), component
								.getY());
			}
		});
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.net.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class Answer_2315 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTree tree;

	private JDesktopPane desktopPane;

	private JLabel iconLabel;

	private JButton pButton;

	private JButton nButton;

	private JScrollPane iconScrollPane;

	private JPanel iconPanel;

	int imgIndex;

	int imgCount;

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Answer_2315 frame = new Answer_2315();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the frame
	 */
	public Answer_2315() {
		super();
		setResizable(false);
		setBounds(0, 0, 1024, 768);
		setExtendedState(Answer_2315.MAXIMIZED_BOTH);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		final JSplitPane splitPane = new JSplitPane();
		splitPane.setDividerLocation(220);
		getContentPane().add(splitPane, BorderLayout.CENTER);

		final JScrollPane treeSscrollPane = new JScrollPane();
		splitPane.setLeftComponent(treeSscrollPane);

		DefaultMutableTreeNode root = new DefaultMutableTreeNode("");

		File[] files = File.listRoots();// 遍历系统根目录
		for (int i = 0; i &lt; files.length; i++) {
			File file = files[i];// 获得跟目录对象
			DefaultMutableTreeNode node = null;
			try {
				node = new DefaultMutableTreeNode(file.getCanonicalPath());
			} catch (IOException e) {
				e.printStackTrace();
			}
			File[] files2 = file.listFiles(fileFilter);// 遍历二级子目录
			if (files2 != null) {
				for (int j = 0; j &lt; files2.length; j++) {
					File file2 = files2[j];// 获得二级子目录对象
					if (file2.isDirectory())
						node.add(new DefaultMutableTreeNode(file2.getName()));
					else
						node.add(new DefaultMutableTreeNode(file2.getName(),
								false));
				}
			}
			root.add(node);
		}

		tree = new JTree(root, true);
		tree.setRootVisible(false);
		tree.addTreeWillExpandListener(new TreeWillExpandListener() {
			public void treeWillExpand(TreeExpansionEvent e)
					throws ExpandVetoException {
				TreePath willExpandPath = e.getPath();
				loadChildNode(willExpandPath);// 加载子目录
			}

			public void treeWillCollapse(TreeExpansionEvent e)
					throws ExpandVetoException {
			}
		});
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				TreePath selectionPath = tree.getSelectionPath();
				loadChildNode(selectionPath);// 加载子目录
				//
				iconPanel.removeAll();
				Object[] nodePath = selectionPath.getPath();
				String selectedDir = nodePath[1].toString().replace("\\", "/");
				for (int i = 2; i &lt; nodePath.length; i++) {
					selectedDir = selectedDir + nodePath[i] + "/";
				}
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
						.getLastPathComponent();
				if (node.getAllowsChildren()) {
					new LoadIconInThread(selectedDir, node).start();
				} else {
					if (pButton.isEnabled())
						pButton.setEnabled(false);
					if (nButton.isEnabled())
						nButton.setEnabled(false);
					showImgInFrame(selectedDir);
				}
				SwingUtilities.updateComponentTreeUI(iconPanel);
			}
		});
		treeSscrollPane.setViewportView(tree);

		final JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		splitPane.setRightComponent(panel);

		desktopPane = new JDesktopPane();
		JLabel backLabel = new JLabel(); // 创建一个标签组件对象
		URL resource = this.getClass().getResource("/bg.jpg"); // 获得背景图片的路径
		ImageIcon icon = new ImageIcon(resource); // 创建背景图片对象
		backLabel.setIcon(icon); // 令标签组件显示背景图片
		backLabel.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight()); // 设置组件的显示位置及大小
		desktopPane.add(backLabel, new Integer(Integer.MIN_VALUE)); // 将标签组件添加到指定索引位置
		panel.add(desktopPane, BorderLayout.CENTER);

		final JPanel operatePanel = new JPanel();
		operatePanel.setLayout(new BorderLayout());
		operatePanel.setPreferredSize(new Dimension(0, 150));
		panel.add(operatePanel, BorderLayout.SOUTH);

		pButton = new JButton();
		pButton.setText("&lt;&lt;");
		pButton.setEnabled(false);
		pButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				imgIndex--;
				JButton button = (JButton) iconPanel.getComponent(imgIndex);
				showImgInFrame(button.getName());
				if (imgIndex == 0)
					pButton.setEnabled(false);
				if (!nButton.isEnabled()) {
					if (imgIndex &lt; imgCount - 1)
						nButton.setEnabled(true);
				}
				button.requestFocus();
			}
		});
		operatePanel.add(pButton, BorderLayout.WEST);

		nButton = new JButton();
		nButton.setText("&gt;&gt;");
		nButton.setEnabled(false);
		nButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				imgIndex++;
				JButton button = (JButton) iconPanel.getComponent(imgIndex);
				showImgInFrame(button.getName());
				if (!pButton.isEnabled()) {
					if (imgIndex &gt; 0)
						pButton.setEnabled(true);
				}
				if (imgIndex == imgCount - 1)
					nButton.setEnabled(false);
				button.requestFocus();
			}
		});
		operatePanel.add(nButton, BorderLayout.EAST);

		iconScrollPane = new JScrollPane();
		iconScrollPane
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
		operatePanel.add(iconScrollPane, BorderLayout.CENTER);

		iconPanel = new JPanel();
		iconScrollPane.setViewportView(iconPanel);
		//
	}

	FileFilter fileFilter = new FileFilter() {
		public boolean accept(File file) {
			if (file.isDirectory())
				return true;
			else {
				String name = file.getName().toUpperCase();
				if (name.endsWith(".JPG"))
					return true;
				else if (name.endsWith(".GIF"))
					return true;
				else
					return false;
			}
		}
	};

	private class PreviewButtonAL implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			showImgInFrame(((JButton) e.getSource()).getName());
		}
	}

	public void showImgInFrame(String imgDir) {
		JInternalFrame frame = desktopPane.getSelectedFrame();
		String imgName = new File(imgDir).getName();
		JInternalFrame[] allFrames = desktopPane.getAllFrames();
		for (int i = 0; i &lt; allFrames.length; i++) {
			JInternalFrame internalFrame = allFrames[i];
			if (internalFrame.getTitle().equals(imgName)) {
				if (internalFrame.isIcon()) {
					try {
						internalFrame.setIcon(false);
					} catch (PropertyVetoException e) {
						e.printStackTrace();
					}
				}
				if (!internalFrame.isSelected()) {
					try {
						internalFrame.setSelected(true);
					} catch (PropertyVetoException e) {
						e.printStackTrace();
					}
				}
				frame = internalFrame;
				break;
			}
		}

		if (frame == null || frame.isIcon()) {
			frame = new JInternalFrame();
			frame.setIconifiable(true);
			frame.setMaximizable(true);
			frame.setBounds(-5, -5, 800, 600);
			desktopPane.add(frame);
			frame.setVisible(true);
			iconLabel = new JLabel();
			frame.getContentPane().add(iconLabel);
		}
		if (!frame.getTitle().equals(imgName)) {
			frame.setTitle(imgName);
			iconLabel.setIcon(new ImageIcon(imgDir));
		}
	}

	public void loadChildNode(TreePath path) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
				.getLastPathComponent();
		if (node.getAllowsChildren() &amp;&amp; node.getChildCount() == 0) {
			StringBuffer dirBuffer = new StringBuffer();
			Object[] nodes = path.getPath();
			for (int i = 0; i &lt; nodes.length; i++) {
				dirBuffer.append(nodes[i]);
				dirBuffer.append("\\");
			}
			File file = new File(dirBuffer.toString());
			File[] files = file.listFiles(fileFilter);
			for (int i = 0; i &lt; files.length; i++) {
				File file2 = files[i];
				if (file2.isDirectory())
					node.add(new DefaultMutableTreeNode(file2.getName()));
				else
					node
							.add(new DefaultMutableTreeNode(file2.getName(),
									false));
			}
		}
	}

	private class LoadIconInThread extends Thread {

		private String selectedDir;

		private DefaultMutableTreeNode node;

		public LoadIconInThread(String selectedDir, DefaultMutableTreeNode node) {
			this.node = node;
			this.selectedDir = selectedDir;
		}

		@Override
		public void run() {
			imgIndex = -1;
			imgCount = 0;
			pButton.setEnabled(false);
			nButton.setEnabled(false);
			int childCount = node.getChildCount();
			for (int i = 0; i &lt; childCount; i++) {
				DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node
						.getChildAt(i);
				if (!childNode.getAllowsChildren()) {
					imgCount++;
					String imgName = childNode.toString();
					MButton button = new MButton();
					button.setText(imgName);
					button.setName(selectedDir + imgName);
					button.setPreferredSize(new Dimension(120, 120));
					button.addActionListener(new PreviewButtonAL());
					iconPanel.add(button);
					iconScrollPane.validate();
					if (!nButton.isEnabled()) {
						if (imgCount &gt; 0)
							nButton.setEnabled(true);
					}
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			System.out.println("文件夹“" + node + "”中的图片加载完毕！");
		}
	}

	private class MButton extends JButton {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		@Override
		protected void paintComponent(Graphics g) {
			int width = getWidth();
			int height = getHeight();
			ImageIcon icon = new ImageIcon(getName());
			g.drawImage(icon.getImage(), 0, 0, width, height - 25, this);
			icon = null;
			g.drawString(getText(), 5, height - 10);
		}

	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="二、高级事件处理"><a href="#二、高级事件处理" class="headerlink" title="二、高级事件处理"></a>二、高级事件处理</h2><h4 id="1-键盘事件（KeyEvent）"><a href="#1-键盘事件（KeyEvent）" class="headerlink" title="1.键盘事件（KeyEvent）"></a>1.键盘事件（KeyEvent）</h4><p>当向文本框中输入内容时，将发出键盘事件。KeyEvent类负责捕获键盘事件，可以通过为组件添加实现了KeyListener接口的监听器类来处理相应的键盘事件。<br>KeyListener接口共有三个抽象方法，分别在发生击键事件、按键被按下和释放时被触发。KeyListener接口的具体定义如下所示：</p>
<pre class="line-numbers language-none"><code class="language-none">public interface KeyListener extends EventListener {
    public void keyTyped(KeyEvent e); 	//发生击键事件时被触发
    public void keyPressed(KeyEvent e); 	//按键被按下时被触发
    public void keyReleased(KeyEvent e); 	//按键被释放时被触发
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217200858.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class KeyEvent_Example extends JFrame { // 继承窗体类JFrame
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		KeyEvent_Example frame = new KeyEvent_Example();
		frame.setVisible(true); // 设置窗体可见，默认为不可见
	}
	
	public KeyEvent_Example() {
		super(); // 继承父类的构造方法
		setTitle("键盘事件示例"); // 设置窗体的标题
		setBounds(100, 100, 500, 375); // 设置窗体的显示位置及大小
		// 设置窗体关闭按钮的动作为退出
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		final JLabel label = new JLabel();
		label.setText("备注：");
		getContentPane().add(label, BorderLayout.WEST);
		final JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		JTextArea textArea = new JTextArea();
		textArea.addKeyListener(new KeyListener() {
			public void keyPressed(KeyEvent e) { // 按键被按下时被触发
				// 获得描述keyCode的标签
				String keyText = KeyEvent.getKeyText(e.getKeyCode());
				if (e.isActionKey()) { // 判断按下的是否为动作键
					System.out.println("您按下的是动作键“" + keyText + "”");
				} else {
					System.out.print("您按下的是非动作键“" + keyText + "”");
					// 获得与此事件中的键相关联的字符
					int keyCode = e.getKeyCode();
					switch (keyCode) {
						case KeyEvent.VK_CONTROL: // 判断按下的是否为Ctrl键
							System.out.print("，Ctrl键被按下");
							break;
						case KeyEvent.VK_ALT: // 判断按下的是否为Alt键
							System.out.print("，Alt键被按下");
							break;
						case KeyEvent.VK_SHIFT: // 判断按下的是否为Shift键
							System.out.print("，Shift键被按下");
							break;
					}
					System.out.println();
				}
			}
			public void keyTyped(KeyEvent e) { // 发生击键事件时被触发
				// 获得输入的字符
				System.out.println("此次输入的是“" + e.getKeyChar() + "”");
			}
			public void keyReleased(KeyEvent e) { // 按键被释放时被触发
				// 获得描述keyCode的标签
				String keyText = KeyEvent.getKeyText(e.getKeyCode());
				System.out.println("您释放的是“" + keyText + "”键");
				System.out.println();
			}
		});
		textArea.setLineWrap(true);
		textArea.setRows(3);
		textArea.setColumns(15);
		scrollPane.setViewportView(textArea);
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-鼠标事件"><a href="#2-鼠标事件" class="headerlink" title="2.鼠标事件"></a>2.鼠标事件</h4><p>所有组件都能发出鼠标事件，MouseEvent类负责捕获鼠标事件，可以通过为组件添加实现了MouseListener接口的监听器类来处理相应的鼠标事件。<br>MouseListener接口共有5个抽象方法，分别在光标移入或移出组件时、鼠标按键被按下或释放时和发生单击事件时被触发。所谓单击事件，就是按键被按下并释放。需要注意的是，如果按键是在移出组件之后才被释放，则不会触发单击事件。</p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217201019.png"></p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217201025.png"></p>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class MouseEvent_Example extends JFrame { // 继承窗体类JFrame
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		MouseEvent_Example frame = new MouseEvent_Example();
		frame.setVisible(true); // 设置窗体可见，默认为不可见
	}
	
	public MouseEvent_Example() {
		super(); // 继承父类的构造方法
		setTitle("鼠标事件示例"); // 设置窗体的标题
		setBounds(100, 100, 500, 375); // 设置窗体的显示位置及大小
		// 设置窗体关闭按钮的动作为退出
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JLabel label = new JLabel();
		label.addMouseListener(new MouseListener() {
			public void mouseEntered(MouseEvent e) {// 光标移入组件时被触发
				System.out.println("光标移入组件");
			}
			
			public void mousePressed(MouseEvent e) {// 鼠标按键被按下时被触发
				System.out.print("鼠标按键被按下，");
				int i = e.getButton(); // 通过该值可以判断按下的是哪个键
				if (i == MouseEvent.BUTTON1)
					System.out.println("按下的是鼠标左键");
				if (i == MouseEvent.BUTTON2)
					System.out.println("按下的是鼠标滚轮");
				if (i == MouseEvent.BUTTON3)
					System.out.println("按下的是鼠标右键");
			}
			
			public void mouseReleased(MouseEvent e) {// 鼠标按键被释放时被触发
				System.out.print("鼠标按键被释放，");
				int i = e.getButton(); // 通过该值可以判断释放的是哪个键
				if (i == MouseEvent.BUTTON1)
					System.out.println("释放的是鼠标左键");
				if (i == MouseEvent.BUTTON2)
					System.out.println("释放的是鼠标滚轮");
				if (i == MouseEvent.BUTTON3)
					System.out.println("释放的是鼠标右键");
			}
			
			public void mouseClicked(MouseEvent e) {// 发生单击事件时被触发
				System.out.print("单击了鼠标按键，");
				int i = e.getButton(); // 通过该值可以判断单击的是哪个键
				if (i == MouseEvent.BUTTON1)
					System.out.print("单击的是鼠标左键，");
				if (i == MouseEvent.BUTTON2)
					System.out.print("单击的是鼠标滚轮，");
				if (i == MouseEvent.BUTTON3)
					System.out.print("单击的是鼠标右键，");
				int clickCount = e.getClickCount();
				System.out.println("单击次数为" + clickCount + "下");
			}
			
			public void mouseExited(MouseEvent e) {// 光标移出组件时被触发
				System.out.println("光标移出组件");
			}
		});
		getContentPane().add(label, BorderLayout.CENTER);
		//
	}
	
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-窗体事件"><a href="#3-窗体事件" class="headerlink" title="3.窗体事件"></a>3.窗体事件</h4><ul>
<li>捕捉窗体焦点变化事件</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;

import javax.swing.JFrame;

public class WindowFocusListener_Example extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static void main(String args[]) {
		WindowFocusListener_Example frame = new WindowFocusListener_Example();
		frame.setVisible(true);
	}
	public WindowFocusListener_Example() {
		super();
		// 为窗体添加焦点事件监听器
		addWindowFocusListener(new MyWindowFocusListener());
		setTitle("捕获窗体焦点事件");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	private class MyWindowFocusListener implements WindowFocusListener {
		public void windowGainedFocus(WindowEvent e) {// 窗口获得焦点时被触发
			System.out.println("窗口获得了焦点！");
		}
		public void windowLostFocus(WindowEvent e) {// 窗口失去焦点时被触发
			System.out.println("窗口失去了焦点！");
		}
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>捕捉窗体状态变化事件</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;

import javax.swing.JFrame;

public class WindowStateListener_Example extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static void main(String args[]) {
		WindowStateListener_Example frame = new WindowStateListener_Example();
		frame.setVisible(true);
	}
	public WindowStateListener_Example() {
		super();
		// 为窗体添加状态事件监听器
		addWindowStateListener(new MyWindowStateListener());
		setTitle("捕获窗体状态事件");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	private class MyWindowStateListener implements WindowStateListener {
		public void windowStateChanged(WindowEvent e) {
			int oldState = e.getOldState();// 获得窗体以前的状态
			int newState = e.getNewState();// 获得窗体现在的状态
			String from = "";// 标识窗体以前状态的中文字符串
			String to = "";// 标识窗体现在状态的中文字符串
			switch (oldState) {// 判断窗台以前的状态
				case Frame.NORMAL:// 窗体处于正常化
					from = "正常化";
					break;
				case Frame.MAXIMIZED_BOTH:// 窗体处于最大化
					from = "最大化";
					break;
				default:// 窗体处于最小化
					from = "最小化";
			}
			switch (newState) {// 判断窗台现在的状态
				case Frame.NORMAL:// 窗体处于正常化
					to = "正常化";
					break;
				case Frame.MAXIMIZED_BOTH:// 窗体处于最大化
					to = "最大化";
					break;
				default:// 窗体处于最小化
					to = "最小化";
			}
			System.out.println(from + "——&gt;" + to);
		}
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>捕捉其他窗体事件</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class WindowListener_Example extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static void main(String args[]) {
		WindowListener_Example frame = new WindowListener_Example();
		frame.setVisible(true);
	}
	public WindowListener_Example() {
		super();
		addWindowListener(new MyWindowListener());// 为窗体添加其他事件监听器
		setTitle("捕获其他窗体事件");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	private class MyWindowListener implements WindowListener {
		public void windowActivated(WindowEvent e) {// 窗体被激活时触发
			System.out.println("窗口被激活！");
		}
		public void windowOpened(WindowEvent e) {// 窗体被打开时触发
			System.out.println("窗口被打开！");
		}
		public void windowIconified(WindowEvent e) {// 窗体被最小化时触发
			System.out.println("窗口被最小化！");
		}
		public void windowDeiconified(WindowEvent e) {// 窗体被非最小化时触发
			System.out.println("窗口被非最小化！");
		}
		public void windowClosing(WindowEvent e) {// 窗体将要被关闭时触发
			System.out.println("窗口将要被关闭！");
		}
		// 窗体不再处于激活状态时触发
		public void windowDeactivated(WindowEvent e) {
			System.out.println("窗口不再处于激活状态！");
		}
		public void windowClosed(WindowEvent e) {// 窗体已经被关闭时触发
			System.out.println("窗口已经被关闭！");
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-选项事件"><a href="#4-选项事件" class="headerlink" title="4.选项事件"></a>4.选项事件</h4><pre class="line-numbers language-none"><code class="language-none">import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class ItemEvent_Example extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		ItemEvent_Example frame = new ItemEvent_Example();
		frame.setVisible(true);
	}

	public ItemEvent_Example() {
		super();
		getContentPane().setLayout(new FlowLayout());
		setTitle("选项事件示例");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JComboBox&lt;String&gt; comboBox = new JComboBox&lt;&gt;();// 创建一个下拉菜单
		for (int i = 1; i &lt; 6; i++) {// 通过循环添加选项
			comboBox.addItem("选项" + i);
		}
		comboBox.addItemListener(new ItemListener() {// 添加选项事件监听器
			public void itemStateChanged(ItemEvent e) {
				int stateChange = e.getStateChange();// 获得事件类型
				String item = e.getItem().toString();// 获得触发此次事件的选项
				if (stateChange == ItemEvent.SELECTED) {// 查看是否由选中选项触发
					System.out.println("此次事件由      选中  选项“" + item + "”触发！");
					// 查看是否由取消选中选项触发
				} else if (stateChange == ItemEvent.DESELECTED) {
					System.out.println("此次事件由  取消选中  选项“" + item + "”触发！");
				} else {// 由其他原因触发
					System.out.println("此次事件由其他原因触发！");
				}
			}
		});
		getContentPane().add(comboBox);
	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="表格模型事件"><a href="#表格模型事件" class="headerlink" title="表格模型事件"></a>表格模型事件</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;

public class TableModelEvent_Example extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTable table;// 声明一个表格对象
	private DefaultTableModel tableModel;// 声明一个表格模型对象
	private JTextField aTextField;
	private JTextField bTextField;
	public static void main(String args[]) {
		TableModelEvent_Example frame = new TableModelEvent_Example();
		frame.setVisible(true);
	}
	public TableModelEvent_Example() {
		super();
		setTitle("表格模型事件示例");
		setBounds(100, 100, 548, 213);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		final JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		String[] columnNames = { "A", "B" };
		String[][] rowValues = { { "A1", "B1" }, { "A2", "B2" },
				{ "A3", "B3" }, { "A4", "B4" } };
		// 创建表格模型对象
		tableModel = new DefaultTableModel(rowValues, columnNames);
		// 为表格模型添加事件监听器
		tableModel.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				int type = e.getType();// 获得事件的类型
				int row = e.getFirstRow() + 1;// 获得触发此次事件的表格行索引
				int column = e.getColumn() + 1;// 获得触发此次事件的表格列索引
				if (type == TableModelEvent.INSERT) {// 判断是否有插入行触发
					System.out.print("此次事件由 插入 行触发，");
					System.out.println("此次插入的是第 " + row + " 行！");
					// 判断是否有修改行触发
				} else if (type == TableModelEvent.UPDATE) {
					System.out.print("此次事件由 修改 行触发，");
					System.out.println("此次修改的是第 " + row + " 行第 " + column
							+ " 列！");
					// 判断是否有删除行触发
				} else if (type == TableModelEvent.DELETE) {
					System.out.print("此次事件由 删除 行触发，");
					System.out.println("此次删除的是第 " + row + " 行！");
				} else {
					System.out.println("此次事件由 其他原因 触发！");
				}
			}
		});
		table = new JTable(tableModel);// 利用表格模型对象创建表格对象
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane.setViewportView(table);
		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.SOUTH);
		final JLabel aLabel = new JLabel("A：");
		panel.add(aLabel);
		aTextField = new JTextField(15);
		panel.add(aTextField);
		final JLabel bLabel = new JLabel("B：");
		panel.add(bLabel);
		bTextField = new JTextField(15);
		panel.add(bTextField);
		final JButton addButton = new JButton("添加");
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String[] rowValues = { aTextField.getText(),
						bTextField.getText() };
				tableModel.addRow(rowValues);// 向表格模型中添加一行
				aTextField.setText(null);
				bTextField.setText(null);
			}
		});
		panel.add(addButton);
		final JButton delButton = new JButton("删除");
		delButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 获得表格中的选中行
				int[] selectedRows = table.getSelectedRows();
				for (int row = 0; row &lt; selectedRows.length; row++) {
					// 从表格模型中移除表格中的选中行
					tableModel.removeRow(selectedRows[row] - row);
				}
			}
		});
		panel.add(delButton);
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="作业-4"><a href="#作业-4" class="headerlink" title="作业"></a>作业</h6><pre class="line-numbers language-none"><code class="language-none">import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Answer_2508 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTextField textField_1;

	private JTextField textField;

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Answer_2508 frame = new Answer_2508();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the frame
	 */
	public Answer_2508() {
		super();
		setTitle("25-8");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);

		final JLabel label = new JLabel();
		label.setText("方式一：");
		panel.add(label);

		textField = new JTextField();
		textField.addKeyListener(new KeyListener() {

			int keyCode;

			public void keyPressed(KeyEvent e) {
				keyCode = e.getKeyCode();
			}

			public void keyTyped(KeyEvent e) {
				if (keyCode &lt; KeyEvent.VK_0 || keyCode &gt; KeyEvent.VK_9)
					e.consume();
			}

			public void keyReleased(KeyEvent e) {
			}

		});
		textField.setColumns(20);
		panel.add(textField);

		final JPanel panel_1 = new JPanel();
		getContentPane().add(panel_1, BorderLayout.CENTER);

		final JLabel label_1 = new JLabel();
		label_1.setText("方式二：");
		panel_1.add(label_1);

		textField_1 = new JTextField();
		textField_1.addKeyListener(new KeyAdapter() {

			String num = "0123456789";

			public void keyTyped(KeyEvent e) {
				if (num.indexOf(e.getKeyChar()) &lt; 0)
					e.consume();
			}

		});
		textField_1.setColumns(20);
		panel_1.add(textField_1);
		//
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

public class Answer_2509 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTextField textField;

	private DefaultTableModel tableModel;

	private JTable table;

	private JLabel label;

	public static void main(String args[]) {
		try {
			Answer_2509 frame = new Answer_2509();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Answer_2509() {
		super();
		setTitle("25-9");
		setBounds(100, 100, 500, 375);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		final JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);

		final JLabel label_1 = new JLabel();
		label_1.setText("数量：");
		panel.add(label_1);

		textField = new JTextField();
		textField.setColumns(10);
		textField.setEditable(false);
		textField.setText((int) (Math.random() * 1000) + "");
		panel.add(textField);

		final JButton button = new JButton();
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] rowValues = { table.getRowCount() + 1,
						Integer.valueOf(textField.getText()) };
				tableModel.addRow(rowValues);
				textField.setText((int) (Math.random() * 1000) + "");
			}
		});
		button.setText("插入");
		panel.add(button);

		final JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);

		String[] columnNames = { "编号", "数量" };

		tableModel = new DefaultTableModel(null, columnNames);
		tableModel.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				int sum = 0;
				for (int i = 0; i &lt; table.getRowCount(); i++) {
					sum += (Integer) tableModel.getValueAt(i, 1);
				}
				label.setText("数量总计：" + sum);
			}
		});

		table = new JTable(tableModel);
		scrollPane.setViewportView(table);

		label = new JLabel();
		label.setText("数量总计：0");
		getContentPane().add(label, BorderLayout.SOUTH);
		//
	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">lxx</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://xinxinliang.github.io/2021/02/19/java-kuo-zhan-lei-1-swing-cheng-xu-she-ji-he-gao-ji-shi-jian/">http://xinxinliang.github.io/2021/02/19/java-kuo-zhan-lei-1-swing-cheng-xu-she-ji-he-gao-ji-shi-jian/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">lxx</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                                    <span class="chip bg-color">编程语言</span>
                                </a>
                            
                                <a href="/tags/Java%E6%89%A9%E5%B1%95%E7%B1%BB/">
                                    <span class="chip bg-color">Java扩展类</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220206.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220308.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/02/19/java-kuo-zhan-lei-2-duo-xian-cheng/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-e7z5vk.jpg" class="responsive-img" alt="Java扩展类2：多线程">
                        
                        <span class="card-title">Java扩展类2：多线程</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-02-19
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                        <span class="chip bg-color">编程语言</span>
                    </a>
                    
                    <a href="/tags/Java%E6%89%A9%E5%B1%95%E7%B1%BB/">
                        <span class="chip bg-color">Java扩展类</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/02/19/java-xue-xi-5-ji-he-lei-io-fan-she-mei-ju-yu-fan-xing/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-dg1eko.png" class="responsive-img" alt="Java学习5：集合类、IO、反射、枚举与泛型">
                        
                        <span class="card-title">Java学习5：集合类、IO、反射、枚举与泛型</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-02-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                        <span class="chip bg-color">编程语言</span>
                    </a>
                    
                    <a href="/tags/Java%E8%AF%AD%E6%B3%95/">
                        <span class="chip bg-color">Java语法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 头号咸鱼<br />'
            + '文章作者: lxx<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">lxx</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">272.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/xinxinliang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1974733812@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1974733812" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1974733812" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "7b318e23"
        });
        daovoice('update');
    </script>
    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
